List of usage examples for java.lang.reflect Field getModifiers
public int getModifiers()
From source file:adalid.core.EntityAtlas.java
private void finaliseFields() { String name;/*from w ww .j a v a2s . c o m*/ Class<?> type; int modifiers; boolean restricted; Object o; int depth = _declaringArtifact.depth(); int round = _declaringArtifact.round(); int index = _declaringArtifact.getStartWith(); Class<?>[] classes = new Class<?>[] { Property.class, Key.class, Tab.class, View.class, Instance.class, NamedValue.class, Expression.class, Transition.class, Operation.class, Trigger.class }; Class<?> dac = _declaringArtifact.getClass(); Class<?> top = Entity.class; for (Class<?> c : classes) { for (Field field : XS1.getFields(dac, top)) { field.setAccessible(true); logger.trace(field); name = field.getName(); type = field.getType(); if (!c.isAssignableFrom(type)) { continue; } if (c.equals(Expression.class) && Property.class.isAssignableFrom(type)) { continue; } modifiers = field.getModifiers(); restricted = Modifier.isPrivate(modifiers); if (restricted) { continue; } restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers); if (restricted) { continue; } String errmsg = "failed to initialize field \"" + field + "\" at " + _declaringArtifact; try { o = field.get(_declaringArtifact); if (o == null) { logger.debug(message(type, name, o, depth, round)); } else if (o instanceof Property) { finaliseProperty(field, (Property) o); } else if (o instanceof Key) { finaliseKey(field, (Key) o); } else if (o instanceof Tab) { finaliseTab(field, (Tab) o); } else if (o instanceof View) { finaliseView(field, (View) o); } else if (o instanceof Instance) { finaliseInstance(field, (Instance) o, index++); } else if (o instanceof NamedValue) { finaliseNamedValue(field, (NamedValue) o); } else if (o instanceof Expression) { finaliseExpression(field, (Expression) o); } else if (o instanceof Transition) { finaliseTransition(field, (Transition) o); } else if (o instanceof Operation) { finaliseOperation(field, (Operation) o); } else if (o instanceof Trigger) { finaliseTrigger(field, (Trigger) o); } } catch (IllegalArgumentException | IllegalAccessException ex) { logger.error(errmsg, ThrowableUtils.getCause(ex)); TLC.getProject().getParser().increaseErrorCount(); } } } }
From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private Object getObject(Class claz, List<Type> heirarchies) throws Exception { if (claz.isEnum()) return claz.getEnumConstants()[0]; if (isMap(claz)) { return getMapValue(claz, claz.getTypeParameters(), heirarchies); } else if (isCollection(claz)) { return getListSetValue(claz, claz.getTypeParameters(), heirarchies); } else if (claz.isInterface() || Modifier.isAbstract(claz.getModifiers())) { return null; }/*from www . j a v a 2 s . c om*/ if (heirarchies.contains(claz) || heirarchies.size() >= 2) return null; heirarchies.add(claz); Constructor cons = null; try { cons = claz.getConstructor(new Class[] {}); } catch (Exception e) { getLog().error("No public no-args constructor found for class " + claz.getName()); return null; } Object object = cons.newInstance(new Object[] {}); List<Field> allFields = getAllFields(claz); for (Field field : allFields) { if (Modifier.isStatic(field.getModifiers())) continue; if (!field.isAccessible()) { field.setAccessible(true); } List<Type> fheirlst = new ArrayList<Type>(heirarchies); if (isDebugEnabled()) getLog().info("Parsing Class " + getHeirarchyStr(fheirlst) + " field " + field.getName() + " type " + field.getType().equals(boolean.class)); if (isPrimitive(field.getType())) { field.set(object, getPrimitiveValue(field.getType())); } else if (isMap(field.getType())) { ParameterizedType type = (ParameterizedType) field.getGenericType(); field.set(object, getMapValue(field.getType(), type.getActualTypeArguments(), fheirlst)); } else if (isCollection(field.getType())) { ParameterizedType type = (ParameterizedType) field.getGenericType(); field.set(object, getListSetValue(field.getType(), type.getActualTypeArguments(), fheirlst)); } else if (!claz.equals(field.getType())) { Object fieldval = getObject(field.getType(), fheirlst); field.set(object, fieldval); } else if (claz.equals(field.getType())) { if (isDebugEnabled()) getLog().info("Ignoring recursive fields..."); } } return object; }
From source file:com.impetus.client.cassandra.query.CassQuery.java
/** * Builds where Clause./*from ww w . j a v a2 s . c o m*/ * * @param kunderaQuery * the kundera query * @param metadata * the metadata * @param metaModel * the meta model * @param translator * the translator * @param builder * the builder */ private void buildWhereClause(KunderaQuery kunderaQuery, EntityMetadata metadata, MetamodelImpl metaModel, CQLTranslator translator, StringBuilder builder) { for (Object clause : kunderaQuery.getFilterClauseQueue()) { FilterClause filterClause = (FilterClause) clause; Field f = (Field) metaModel.entity(metadata.getEntityClazz()) .getAttribute(metadata.getFieldName(filterClause.getProperty())).getJavaMember(); String jpaColumnName = getColumnName(metadata, filterClause.getProperty()); if (metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) { Field[] fields = metadata.getIdAttribute().getBindableJavaType().getDeclaredFields(); EmbeddableType compoundKey = metaModel.embeddable(metadata.getIdAttribute().getBindableJavaType()); for (Field field : fields) { if (field != null && !Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers()) && !field.isAnnotationPresent(Transient.class)) { Attribute attribute = compoundKey.getAttribute(field.getName()); String columnName = ((AbstractAttribute) attribute).getJPAColumnName(); Object value = PropertyAccessorHelper.getObject(filterClause.getValue().get(0), field); // TODO translator.buildWhereClause(builder, field.getType(), columnName, value, filterClause.getCondition(), false); } } } else { translator.buildWhereClause(builder, f.getType(), jpaColumnName, filterClause.getValue().get(0), filterClause.getCondition(), false); } } builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length()); }
From source file:com.oembedler.moon.graphql.engine.dfs.GraphQLSchemaDfsTraversal.java
public GraphQLFieldDefinition getFieldDefinition(DfsContext dfsContext, Class<?> implClass, Field field) { GraphQLFieldDefinition graphQLFieldDefinition = null; ResolvableTypeAccessor resolvableTypeAccessor = ResolvableTypeAccessor.forField(field, implClass); if (resolvableTypeAccessor.isNotIgnorable()) { GraphQLOutputType graphQLOutputType = (GraphQLOutputType) createGraphQLFieldType(dfsContext, resolvableTypeAccessor, true); GraphQLFieldDefinition.Builder graphQLFieldDefinitionBuilder = GraphQLFieldDefinition .newFieldDefinition().name(resolvableTypeAccessor.getName()).type(graphQLOutputType) .deprecate(resolvableTypeAccessor.getGraphQLDeprecationReason()) .description(resolvableTypeAccessor.getDescription()); boolean isConstant = Modifier.isFinal(field.getModifiers()) && Modifier.isStatic(field.getModifiers()); if (isConstant) { graphQLFieldDefinitionBuilder .staticValue(org.springframework.util.ReflectionUtils.getField(field, null)); }//from w w w. j av a 2 s . co m graphQLFieldDefinition = graphQLFieldDefinitionBuilder.build(); addToFieldDefinitionResolverMap(dfsContext, graphQLFieldDefinition, resolvableTypeAccessor.getGraphQLComplexitySpelExpression()); } return graphQLFieldDefinition; }
From source file:net.minecraftforge.fml.common.FMLModContainer.java
private void parseSimpleFieldAnnotation(SetMultimap<String, ASMData> annotations, String annotationClassName, Function<ModContainer, Object> retriever) throws IllegalAccessException { String[] annName = annotationClassName.split("\\."); String annotationName = annName[annName.length - 1]; for (ASMData targets : annotations.get(annotationClassName)) { String targetMod = (String) targets.getAnnotationInfo().get("value"); Field f = null; Object injectedMod = null; ModContainer mc = this; boolean isStatic = false; Class<?> clz = modInstance.getClass(); if (!Strings.isNullOrEmpty(targetMod)) { if (Loader.isModLoaded(targetMod)) { mc = Loader.instance().getIndexedModList().get(targetMod); } else { mc = null;/* w ww. j a va2s .c o m*/ } } if (mc != null) { try { clz = Class.forName(targets.getClassName(), true, Loader.instance().getModClassLoader()); f = clz.getDeclaredField(targets.getObjectName()); f.setAccessible(true); isStatic = Modifier.isStatic(f.getModifiers()); injectedMod = retriever.apply(mc); } catch (Exception e) { Throwables.propagateIfPossible(e); FMLLog.log(getModId(), Level.WARN, e, "Attempting to load @%s in class %s for %s and failing", annotationName, targets.getClassName(), mc.getModId()); } } if (f != null) { Object target = null; if (!isStatic) { target = modInstance; if (!modInstance.getClass().equals(clz)) { FMLLog.log(getModId(), Level.WARN, "Unable to inject @%s in non-static field %s.%s for %s as it is NOT the primary mod instance", annotationName, targets.getClassName(), targets.getObjectName(), mc.getModId()); continue; } } f.set(target, injectedMod); } } }
From source file:org.apache.hadoop.hbase.client.TestHCM.java
private int setNumTries(HConnectionImplementation hci, int newVal) throws Exception { Field numTries = hci.getClass().getDeclaredField("numTries"); numTries.setAccessible(true);/*from w w w . j a va2 s .c o m*/ Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(numTries, numTries.getModifiers() & ~Modifier.FINAL); final int prevNumRetriesVal = (Integer) numTries.get(hci); numTries.set(hci, newVal); return prevNumRetriesVal; }
From source file:org.soyatec.windowsazure.table.internal.CloudTableRest.java
/** * Deserial the xml to object accord to the give model class. * * @param partitionKey/* w w w . j a va2 s. co m*/ * @param rowKey * @param eTag * @param timestamp * @param values * @return Instance of the given model class. */ private ITableServiceEntity createObjectByModelClass(String partitionKey, String rowKey, String eTag, String timestamp, List<ICloudTableColumn> values) { ITableServiceEntity newInstance = instanceModel(partitionKey, rowKey, eTag, timestamp, values); if (newInstance == null) { return null; } // Copy Field if (values != null && !values.isEmpty()) { for (ICloudTableColumn column : values) { Field field = null; try { field = newInstance.getClass().getDeclaredField(column.getName()); } catch (NoSuchFieldException e) { continue; } if (field == null) { continue; } int modifier = field.getModifiers(); if (Modifier.isPrivate(modifier) && Modifier.isFinal(modifier) && Modifier.isStatic(modifier)) { if (getModelClass() != null) { Logger.debug(MessageFormat.format( "{0} class {1} is a static final field. Can not set data to it.", getModelClass().getClass(), field.getName())); } continue; } boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(true); } ETableColumnType type = column.getType(); String value = column.getValue(); if (value == null) { continue; } else { try { if (type == null) { setStringOrObjectField(newInstance, column, field, value); } else if (type.equals(ETableColumnType.TYPE_BINARY)) { field.set(newInstance, Base64.decode(value)); } else if (type.equals(ETableColumnType.TYPE_BOOL)) { field.setBoolean(newInstance, Boolean.parseBoolean(value)); } else if (type.equals(ETableColumnType.TYPE_DATE_TIME)) { field.set(newInstance, Utilities.tryGetDateTimeFromTableEntry(value)); } else if (type.equals(ETableColumnType.TYPE_DOUBLE)) { field.setDouble(newInstance, Double.parseDouble(value)); } else if (type.equals(ETableColumnType.TYPE_GUID)) { Guid guid = new Guid(); try { Field valueField = guid.getClass().getDeclaredField("value"); boolean accessiable = valueField.isAccessible(); if (!accessible) { valueField.setAccessible(true); } valueField.set(guid, value); valueField.setAccessible(accessiable); field.set(newInstance, guid); } catch (NoSuchFieldException e) { Logger.error(e.getMessage(), e); } } else if (type.equals(ETableColumnType.TYPE_INT)) { try { field.setInt(newInstance, Integer.parseInt(value)); } catch (Exception e) { field.setByte(newInstance, Byte.parseByte(value)); } } else if (type.equals(ETableColumnType.TYPE_LONG)) { field.setLong(newInstance, Long.parseLong(value)); } else if (type.equals(ETableColumnType.TYPE_STRING)) { setStringOrObjectField(newInstance, column, field, value); } } catch (Exception e) { Logger.error( MessageFormat.format("{0} class filed {1} set failed.", getModelClass(), value), e); } } // revert aaccessible field.setAccessible(accessible); } } return newInstance; }
From source file:org.apache.click.service.XmlConfigService.java
/** * Return the fields annotated with the Bindable annotation. * * @param pageClass the page class// w w w .j av a 2s.co m * @return the map of bindable fields */ private static Map getAnnotatedBindableFields(Class pageClass) { List<Class> pageClassList = new ArrayList<Class>(); pageClassList.add(pageClass); Class parentClass = pageClass.getSuperclass(); while (parentClass != null) { // Include parent classes up to but excluding Page.class if (parentClass.isAssignableFrom(Page.class)) { break; } pageClassList.add(parentClass); parentClass = parentClass.getSuperclass(); } // Reverse class list so parents are processed first, with the // actual page class fields processed last. This will enable the // page classes fields to override parent class fields Collections.reverse(pageClassList); Map<String, Field> fieldMap = new TreeMap<String, Field>(); for (Class aPageClass : pageClassList) { for (Field field : aPageClass.getDeclaredFields()) { if (field.getAnnotation(Bindable.class) != null) { fieldMap.put(field.getName(), field); // If field is not public set accessibility true if (!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } } } } return fieldMap; }
From source file:ca.sqlpower.object.PersistedSPObjectTest.java
/** * All persistable {@link SPObject} implementations must define a static * final field which is a list defining the absolute ordering of that * class's child type classes. This method ensures that list is retrievable * by reflection from the object, that the field is public, static, and * final, and that it is nonempty for classes that allow children and empty * for classes that do not allow children. *//*from w w w . ja v a2 s . c om*/ @SuppressWarnings("unchecked") public void testAllowedChildTypesField() throws Exception { Class<? extends SPObject> classUnderTest = getSPObjectUnderTest().getClass(); Field childOrderField; try { childOrderField = classUnderTest.getDeclaredField("allowedChildTypes"); } catch (NoSuchFieldException ex) { fail("Persistent " + classUnderTest + " must have a static final field called allowedChildTypes"); throw new AssertionError(); // NOTREACHED } assertEquals("The allowedChildTypes field must be final", true, Modifier.isFinal(childOrderField.getModifiers())); assertEquals("The allowedChildTypes field must be static", true, Modifier.isStatic(childOrderField.getModifiers())); // Note: in the future, we will change this to require that the field is private assertEquals("The allowedChildTypes field must be public", true, Modifier.isPublic(childOrderField.getModifiers())); List<Class<? extends SPObject>> allowedChildTypes = (List<Class<? extends SPObject>>) childOrderField .get(null); if (getSPObjectUnderTest().allowsChildren()) { assertFalse(allowedChildTypes.isEmpty()); } else { assertTrue(allowedChildTypes.isEmpty()); } }
From source file:adalid.core.Operation.java
void initialiseFields(Class<?> clazz) { Class<?> c;/*from www. j av a2 s. com*/ int d, r; String name; Class<?> type; int modifiers; boolean restricted; Object o; int depth = depth(); int round = round(); Class<?>[] classes = new Class<?>[] { Parameter.class, Expression.class }; Class<?> dac = getClass(); Class<?> top = Operation.class; int i = ArrayUtils.indexOf(classes, clazz); if (i != ArrayUtils.INDEX_NOT_FOUND) { c = classes[i]; for (Field field : XS1.getFields(dac, top)) { field.setAccessible(true); logger.trace(field); name = field.getName(); type = field.getType(); if (!c.isAssignableFrom(type)) { continue; } modifiers = type.getModifiers(); if (type.isInterface() && Expression.class.isAssignableFrom(type)) { restricted = false; } else { restricted = Modifier.isAbstract(modifiers); } restricted = restricted || !Modifier.isPublic(modifiers); if (restricted) { continue; } modifiers = field.getModifiers(); restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers); if (restricted) { continue; } String errmsg = "failed to create a new instance of field \"" + field + "\" at " + this; try { o = field.get(this); if (o == null) { logger.debug(message(type, name, o, depth, round)); o = XS1.initialiseField(this, field); if (o == null) { logger.debug(message(type, name, o, depth, round)); // throw new RuntimeException(message(type, name, o, depth, round)); } else { logger.debug(message(type, name, o, depth, round)); field.set(this, o); } } } catch (IllegalArgumentException | IllegalAccessException ex) { throw new InstantiationRuntimeException(errmsg, ex); } } } }