List of usage examples for java.lang.reflect Field getGenericType
public Type getGenericType()
From source file:utils.jpa.EntityResource.java
@GET @Path("entity-field-types") public Map<String, String> types() { HashMap<String, String> types = new HashMap<>(); for (Field field : entityClass.getDeclaredFields()) { types.put(field.getName(), field.getGenericType().toString()); }//w w w. ja v a 2s . c o m return types; }
From source file:org.polymap.rhei.batik.engine.PanelContextInjector.java
@Override public void run() { Queue<Class> types = new ArrayDeque(16); types.add(panel.getClass());//from ww w. j av a 2 s . c o m while (!types.isEmpty()) { Class type = types.remove(); if (type.getSuperclass() != null) { types.add(type.getSuperclass()); } for (Field f : type.getDeclaredFields()) { // ContextProperty if (Context.class.isAssignableFrom(f.getType())) { f.setAccessible(true); Type ftype = f.getGenericType(); if (ftype instanceof ParameterizedType) { // set try { f.set(panel, new ContextPropertyInstance(f, context)); log.debug("injected: " + f.getName() + " (" + panel.getClass().getSimpleName() + ")"); continue; } catch (Exception e) { throw new RuntimeException(e); } } else { throw new IllegalStateException("ContextProperty has no type param: " + f.getName()); } } // @Context annotation Scope annotation = f.getAnnotation(Scope.class); if (annotation != null) { f.setAccessible(true); throw new UnsupportedOperationException("Injecting context property as direct member."); // Object value = context.get( f.getType() ); // // try { // f.set( panel, value ); // log.info( "injected: " + f.getName() + " <- " + value ); // } // catch (Exception e) { // throw new RuntimeException( e ); // } } } } }
From source file:org.openmainframe.ade.impl.PropertyAnnotation.java
@SuppressWarnings({ "unchecked" }) static private void setProps(Object obj, Map<String, ? extends Object> props, Pattern filter, boolean safe) throws MissingPropertyException, IllegalArgumentException { final Class<?> annotatedClass = obj.getClass(); final Set<String> keyset = new TreeSet<String>(props.keySet()); for (Field field : annotatedClass.getDeclaredFields()) { final Property annos = field.getAnnotation(Property.class); if (annos != null) { // skip missing and non-required properties final String key = annos.key(); if (!props.containsKey(key)) { if (annos.required()) { throw new MissingPropertyException("Missing property: " + key); } else { // no value for non-required property continue; }//from w w w . j a va 2 s .c o m } final Class<? extends IPropertyFactory<?>> factoryClass = annos.factory(); final Object rawVal = props.get(key); final Type fieldType = field.getGenericType(); Object val = null; if (factoryClass != Property.NULL_PROPERTY_FACTORY.class) { // check if this factory is eligible for creating this property final Type factoryProductType = resolveActualTypeArgs(factoryClass, IPropertyFactory.class)[0]; if (!TypeUtils.isAssignable(factoryProductType, fieldType)) { throw new IllegalArgumentException("The factory provided for the field: " + field.getName() + " is not compatible for creating object of type: " + fieldType); } Constructor<? extends IPropertyFactory<?>> constructor; try { constructor = factoryClass.getConstructor(); } catch (Exception e) { throw new IllegalArgumentException( "Missing empty constructor in: " + factoryClass.getName(), e); } IPropertyFactory<?> factory; try { factory = constructor.newInstance(); } catch (Exception e) { throw new IllegalArgumentException("Failed instantiating: " + factoryClass.getName(), e); } try { val = factory.create(rawVal); } catch (Exception e) { throw new IllegalArgumentException("Failed extractring property value: " + key, e); } } else if (TypeUtils.isAssignable(rawVal.getClass(), fieldType)) { val = rawVal; } else if (rawVal.getClass().equals(String.class)) { final Class<?> fieldClass = field.getType(); final String stringVal = (String) rawVal; if (fieldClass == Integer.class || fieldClass == int.class) { try { val = Integer.parseInt(stringVal); } catch (Exception e) { throw new IllegalArgumentException("Failed parsing integer value for property: " + key, e); } } else if (fieldClass == Double.class || fieldClass == double.class) { try { val = Double.parseDouble(stringVal); } catch (Exception e) { throw new IllegalArgumentException("Failed parsing double value for property: " + key, e); } } else if (fieldClass == Boolean.class || fieldClass == boolean.class) { try { val = Boolean.parseBoolean(stringVal); } catch (Exception e) { throw new IllegalArgumentException("Failed parsing boolean value for property: " + key, e); } } else if (fieldClass == String.class) { // should never have reached here, since String is assignable from String val = stringVal; } else if (fieldClass.isEnum()) { Class<Enum> fieldEnum; try { fieldEnum = (Class<Enum>) fieldClass; } catch (ClassCastException e) { throw new IllegalArgumentException( "Failed casting to Class<Enum> field class: " + fieldClass.getName(), e); } try { val = Enum.valueOf(fieldEnum, stringVal); } catch (Exception e) { throw new IllegalArgumentException("Failed parsing enum value for property: " + key + "\n\t possible values: " + Arrays.toString(fieldEnum.getEnumConstants()), e); } } else { // try to find String constructor for field, or else throw exception Constructor<?> constructor; try { constructor = fieldClass.getConstructor(String.class); } catch (Exception e) { throw new IllegalArgumentException("Field: " + field.getName() + " of type " + fieldClass + " is not one of the known property type (Integer, Double, Boolean, String, Enum), does not have a String constructor and no custom factory is defined in the annotation!", e); } try { val = constructor.newInstance(stringVal); } catch (Exception e) { throw new IllegalArgumentException("Could not create a new instance for " + field.getName() + " using the String constructor for type: " + fieldClass, e); } } } if (val == null) { throw new IllegalArgumentException("For the key " + key + ", we expect the value to be either assignable to " + fieldType + " or a String"); } try { field.setAccessible(true); field.set(obj, val); keyset.remove(key); } catch (SecurityException e) { throw new SecurityException("Field " + field.getName() + " is not accesible, and could not be set as accesible (probably due to PermissionManager)", e); } catch (Exception e) { throw new IllegalArgumentException( "Failed setting field: " + field.getName() + " with value: " + val, e); } } } if (safe && !keyset.isEmpty()) { throw new IllegalArgumentException("Unrecongnized arguments in the properties: " + keyset.toString()); } }
From source file:de.topicmapslab.kuria.runtime.util.TypeUtilTest.java
@SuppressWarnings("unchecked") @Test/* w w w . j a v a 2 s . co m*/ public void testGetContainerType() { String[] tmp3 = new String[10]; assertEquals("Check String array: ", String.class, TypeUtil.getContainerType(tmp3.getClass())); String tmp4[] = new String[10]; assertEquals("Check String array: ", String.class, TypeUtil.getContainerType(tmp4.getClass())); try { Field field = TypeUtilTest.class.getDeclaredField("stringList"); assertEquals("Check List: ", String.class, TypeUtil.getContainerType(field.getGenericType())); assertTrue("Check Vector: ", TypeUtil.isList(field.getGenericType())); field = TypeUtilTest.class.getDeclaredField("stringList2"); assertEquals("Check ArrayListV: ", String.class, TypeUtil.getContainerType(field.getGenericType())); assertTrue("Check Vector: ", TypeUtil.isList(field.getGenericType())); field = TypeUtilTest.class.getDeclaredField("stringList3"); assertEquals("Check Vector: ", String.class, TypeUtil.getContainerType(field.getGenericType())); assertTrue("Check Vector: ", TypeUtil.isList(field.getGenericType())); field = TypeUtilTest.class.getDeclaredField("stack"); assertEquals("Check Stack: ", Object.class, TypeUtil.getContainerType(field.getGenericType())); field = TypeUtilTest.class.getDeclaredField("set1"); assertEquals("Check Sets Parameter: ", Integer.class, TypeUtil.getContainerType(field.getGenericType())); assertTrue("Check Set: ", TypeUtil.isSet(field.getGenericType())); field = TypeUtilTest.class.getDeclaredField("set2"); assertEquals("Check HashSet: ", Integer.class, TypeUtil.getContainerType(field.getGenericType())); assertTrue("Check HashSet: ", TypeUtil.isSet(field.getGenericType())); field = TypeUtilTest.class.getDeclaredField("set3"); assertEquals("Check untyped Set: ", Object.class, TypeUtil.getContainerType(field.getGenericType())); } catch (Exception e) { throw new RuntimeException(e); } // expecting object because no real reflection possible on var types. List<String> tmp = new ArrayList<String>(); assertEquals("Check ArrayList: ", Object.class, TypeUtil.getContainerType(tmp.getClass())); tmp = new ArrayStack(); assertEquals("Check ArrayList: ", Object.class, TypeUtil.getContainerType(tmp.getClass())); tmp = new Vector<String>(); assertEquals("Check ArrayList: ", Object.class, TypeUtil.getContainerType(tmp.getClass())); Set<Integer> tmp2 = new HashSet<Integer>(); assertEquals("Check HashSet: ", Object.class, TypeUtil.getContainerType(tmp2.getClass())); try { TypeUtil.getContainerType(String.class); } catch (IllegalArgumentException e) { return; } fail("No exception thrown"); }
From source file:com.khubla.cbean.serializer.impl.json.JSONListFieldSerializer.java
@Override public String serialize(Object o, Field field) throws SerializerException { try {/*from w w w .java 2 s. co m*/ /* * get the parameterized type */ final ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); final Class<?> containedType = (Class<?>) parameterizedType.getActualTypeArguments()[0]; /* * get cBean */ final CBean<Object> cBean = CBeanServer.getInstance().getCBean(containedType); /* * get the list */ @SuppressWarnings("unchecked") final List<Object> list = (List<Object>) PropertyUtils.getProperty(o, field.getName()); /* * iterate and save contained objects */ final Property property = field.getAnnotation(Property.class); if (property.cascadeSave() == true) { for (int i = 0; i < list.size(); i++) { cBean.save(list.get(i)); } } /* * iterate and grab the keys */ final List<String> keys = new ArrayList<String>(); for (int i = 0; i < list.size(); i++) { final String key = cBean.getId(list.get(i)); keys.add(key); } final JSONArray jsonArray = new JSONArray(keys); return jsonArray.toString(); } catch (final Exception e) { throw new SerializerException(e); } }
From source file:org.broadleafcommerce.openadmin.server.dao.provider.metadata.AbstractFieldMetadataProvider.java
protected FieldInfo buildFieldInfo(Field field) { FieldInfo info = new FieldInfo(); info.setName(field.getName());//w ww. j a va 2 s . c o m info.setGenericType(field.getGenericType()); ManyToMany manyToMany = field.getAnnotation(ManyToMany.class); if (manyToMany != null) { info.setManyToManyMappedBy(manyToMany.mappedBy()); info.setManyToManyTargetEntity(manyToMany.targetEntity().getName()); } OneToMany oneToMany = field.getAnnotation(OneToMany.class); if (oneToMany != null) { info.setOneToManyMappedBy(oneToMany.mappedBy()); info.setOneToManyTargetEntity(oneToMany.targetEntity().getName()); } MapKey mapKey = field.getAnnotation(MapKey.class); if (mapKey != null) { info.setMapKey(mapKey.name()); } return info; }
From source file:com.khubla.cbean.serializer.impl.json.JSONListFieldSerializer.java
@Override public void deserialize(Object o, Field field, String value) throws SerializerException { try {/*from w w w. j av a 2 s . c om*/ /* * get the parameterized type */ final ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); final Class<?> containedType = (Class<?>) parameterizedType.getActualTypeArguments()[0]; /* * get cBean */ final CBean<?> cBean = CBeanServer.getInstance().getCBean(containedType); /* * get the array object */ @SuppressWarnings("unchecked") final List<Object> list = (List<Object>) PropertyUtils.getProperty(o, field.getName()); /* * iterate */ final JSONArray jsonArray = new JSONArray(value); for (int i = 0; i < jsonArray.length(); i++) { final String key = jsonArray.getString(i); final Object oo = cBean.load(new CBeanKey(key)); /* * oo could be null. if that happens, it can be because the underlying object has been deleted. this is ok. We add the null into the the list so that we preserve the list LENGTH */ list.add(oo); } } catch (final Exception e) { throw new SerializerException(e); } }
From source file:com.conversantmedia.mapreduce.tool.annotation.handler.MaraAnnotationUtil.java
/** * If this is a multiple output we're annotating, see if there are type parameters to * use for the key/value classes.//from w w w . j av a2 s . com * @param field the field to inspect * @return the type parameters of the specified field. */ protected Type[] getGenericTypeParams(Field field) { Type genericType = field.getGenericType(); if (genericType instanceof ParameterizedType) { return ((ParameterizedType) genericType).getActualTypeArguments(); } return null; }
From source file:org.polymap.core.model2.store.feature.FeatureTypeBuilder.java
protected ComplexType buildComplexType(Class<? extends Composite> compositeClass) throws Exception { // fields -> properties Collection<PropertyDescriptor> properties = new ArrayList(); Class superClass = compositeClass; for (; superClass != null; superClass = superClass.getSuperclass()) { for (Field field : superClass.getDeclaredFields()) { if (Property.class.isAssignableFrom(field.getType())) { Class<?> binding = (Class) ((ParameterizedType) field.getGenericType()) .getActualTypeArguments()[0]; boolean isNillable = field.getAnnotation(Nullable.class) != null; Object defaultValue = DefaultValues.valueOf(field); // attribute if (binding.isPrimitive() || binding.equals(String.class) || Number.class.isAssignableFrom(binding) || Boolean.class.isAssignableFrom(binding) || Date.class.isAssignableFrom(binding)) { AttributeType propType = buildAttributeType(field, binding); properties.add(factory.createAttributeDescriptor(propType, propType.getName(), 0, 1, isNillable, defaultValue)); }/*from ww w . j av a 2 s . c om*/ // geometry else if (Geometry.class.isAssignableFrom(binding)) { AttributeType propType = buildAttributeType(field, binding); GeometryType geomType = factory.createGeometryType(propType.getName(), propType.getBinding(), crs, propType.isIdentified(), propType.isAbstract(), propType.getRestrictions(), propType.getSuper(), propType.getDescription()); properties.add(factory.createGeometryDescriptor(geomType, geomType.getName(), 0, 1, isNillable, defaultValue)); } // complex else if (Composite.class.isAssignableFrom(binding)) { ComplexType propType = buildComplexType((Class<? extends Composite>) binding); } else { // XXX no collections yet throw new RuntimeException("Type of property is not supported yet: " + binding); } } } } NameInStore nameInStore = compositeClass.getAnnotation(NameInStore.class); Name name = buildName(nameInStore != null ? nameInStore.value() : compositeClass.getSimpleName()); boolean isIdentified = false; boolean isAbstract = false; List<Filter> restrictions = null; AttributeType superType = null; Description annotation = compositeClass.getAnnotation(Description.class); InternationalString description = annotation != null ? SimpleInternationalString.wrap(annotation.value()) : null; return factory.createComplexType(name, properties, isIdentified, isAbstract, restrictions, superType, description); }
From source file:org.vulpe.controller.struts.interceptor.MultiselectInterceptor.java
/** * Just as the CheckboxInterceptor checks that if only the hidden field is * present, so too does this interceptor. If the "__multiselect_" request * parameter is present and its visible counterpart is not, set a new * request parameter to an empty Sting./* ww w .jav a 2s . c om*/ * * @param actionInvocation * ActionInvocation * @return the result of the action * @throws Exception * if error * @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation) */ @Override public String intercept(final ActionInvocation actionInvocation) throws Exception { final Map parameters = actionInvocation.getInvocationContext().getParameters(); final Map<String, Object> newParams = new HashMap<String, Object>(); final Set<String> keys = parameters.keySet(); for (final Iterator<String> iterator = keys.iterator(); iterator.hasNext();) { final String key = iterator.next(); if (key.startsWith("__multiselect_")) { final String name = key.substring("__multiselect_".length()); iterator.remove(); // is this multi-select box submitted? if (parameters.containsKey(name)) { final Object[] values = (Object[]) parameters.get(name); if (values != null) { final VulpeStrutsController baseAction = VulpeReflectUtil.getFieldValue(actionInvocation, "action"); final Object entity = baseAction.vulpe.controller().config().getEntityClass().newInstance(); final String attributeName = name.contains("entities") ? name.substring(name.indexOf("].") + 2) : name.substring("entity.".length()); if (String[].class.isAssignableFrom(values.getClass())) { final Field field = VulpeReflectUtil.getField(entity.getClass(), attributeName); if (List.class.isAssignableFrom(field.getType())) { final Type[] fieldListType = VulpeReflectUtil.getFieldValue(field.getGenericType(), "actualTypeArguments"); final Object[] enumConstants = VulpeReflectUtil.getFieldValue(fieldListType[0], "enumConstants"); if (!ArrayUtils.isEmpty(enumConstants)) { final List list = new ArrayList(); for (Object eConstant : enumConstants) { for (Object value : values) { if (eConstant.toString().equals(value.toString())) { list.add(eConstant); } } } newParams.put(name, list); } } } } } else { // if not, let's be sure to default the value to an empty // string array newParams.put(name, new String[0]); } } } parameters.putAll(newParams); return actionInvocation.invoke(); }