List of usage examples for java.lang.reflect Field getModifiers
public int getModifiers()
From source file:com.jwebmp.core.htmlbuilder.javascript.JavaScriptPart.java
/** * Renders the fields (getDeclaredFields()) as a map of html attributes * * @return//from w w w . j av a2 s .c o m */ public Map<String, String> toAttributes() { Map<String, String> map = new LinkedHashMap<>(); Field[] fields = getClass().getDeclaredFields(); for (Field field : fields) { if (Modifier.isFinal(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) { continue; } field.setAccessible(true); try { Object result = field.get(this); if (result != null) { if (JavaScriptPart.class.isAssignableFrom(result.getClass())) { map.put(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, field.getName()), ((JavaScriptPart) result).toString(true)); } else { map.put(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, field.getName()), result.toString()); } } } catch (Exception e) { JavaScriptPart.log.log(Level.WARNING, "Cant format as attributes", e); } } return map; }
From source file:fi.mystes.synapse.mediator.vfs.VfsFileTransferUtilityTest.java
private Log applyMockLog(final LockFileVerifier verifier) throws NoSuchFieldException, IllegalAccessException { Log log = mock(Log.class); if (verifier != null) { doAnswer(new Answer<Void>() { @Override// w ww . j a v a 2s .co m public Void answer(InvocationOnMock invocation) throws Throwable { verifier.verify(); return null; } }).when(log).debug(expectedLockFileDebugString(verifier)); } Field field = VfsFileTransferUtility.class.getDeclaredField("log"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, log); return log; }
From source file:org.nuxeo.client.api.objects.Document.java
/** * This constructor is providing a way to create 'adapters' of a document. See * org.nuxeo.client.test.objects.DataSet in nuxeo-java-client-test. * * @since 1.0/* w w w .ja v a2s. c om*/ * @param document the document to copy from the sub class. */ public Document(Document document) { super(ConstantsV1.ENTITY_TYPE_DOCUMENT); type = ConstantsV1.DEFAULT_DOC_TYPE; for (Field field : document.getClass().getDeclaredFields()) { if (!Modifier.isFinal(field.getModifiers())) { try { Class<?> superclass = this.getClass().getSuperclass(); if (superclass.equals(NuxeoEntity.class)) { throw new NuxeoClientException( "You should never use this constructor unless you're using a subclass of Document"); } superclass.getDeclaredField(field.getName()).set(this, field.get(document)); } catch (NoSuchFieldException | IllegalAccessException reason) { throw new NuxeoClientException(reason); } } } }
From source file:com.adaptris.core.runtime.AdapterRegistry.java
@Override public String getClassDefinition(String className) throws CoreException { final ClassDescriptor classDescriptor = new ClassDescriptor(className); try {//from w w w . j a v a 2 s . c o m Class<?> clazz = Class.forName(className); classDescriptor.setClassType(ClassDescriptor.ClassType.getTypeForClass(clazz).name().toLowerCase()); List<String> displayOrder = new ArrayList<>(); for (Annotation annotation : clazz.getAnnotations()) { if (XStreamAlias.class.isAssignableFrom(annotation.annotationType())) { classDescriptor.setAlias(((XStreamAlias) annotation).value()); } else if (ComponentProfile.class.isAssignableFrom(annotation.annotationType())) { classDescriptor.setTags(((ComponentProfile) annotation).tag()); classDescriptor.setSummary(((ComponentProfile) annotation).summary()); } else if (DisplayOrder.class.isAssignableFrom(annotation.annotationType())) { displayOrder = Arrays.asList(((DisplayOrder) annotation).order()); } } for (Field field : clazz.getDeclaredFields()) { if ((!Modifier.isStatic(field.getModifiers())) && (field.getDeclaredAnnotation(Transient.class) == null)) { // if we're not transient ClassDescriptorProperty fieldProperty = new ClassDescriptorProperty(); fieldProperty.setOrder( displayOrder.contains(field.getName()) ? displayOrder.indexOf(field.getName()) + 1 : 999); fieldProperty.setAdvanced(false); fieldProperty.setClassName(field.getType().getName()); fieldProperty.setType(field.getType().getSimpleName()); fieldProperty.setName(field.getName()); fieldProperty.setAutoPopulated(field.getDeclaredAnnotation(AutoPopulated.class) != null); fieldProperty.setNullAllowed(field.getDeclaredAnnotation(NotNull.class) != null); for (Annotation annotation : field.getDeclaredAnnotations()) { if (AdvancedConfig.class.isAssignableFrom(annotation.annotationType())) { fieldProperty.setAdvanced(true); } else if (InputFieldDefault.class.isAssignableFrom(annotation.annotationType())) { fieldProperty.setDefaultValue(((InputFieldDefault) annotation).value()); } } classDescriptor.getClassDescriptorProperties().add(fieldProperty); } } try (ScanResult result = new ClassGraph().enableAllInfo().blacklistPackages(FCS_BLACKLIST).scan()) { List<String> subclassNames = result.getSubclasses(className).getNames(); for (String subclassName : subclassNames) { classDescriptor.getSubTypes().add(subclassName); } } } catch (ClassNotFoundException e) { throw new CoreException(e); } return new XStreamJsonMarshaller().marshal(classDescriptor); }
From source file:com.qmetry.qaf.automation.data.BaseDataBean.java
/** * This will fill random data except those properties which has skip=true in * {@link Randomizer} annotation. Use {@link Randomizer} annotation to * specify data value to be generated for specific property. * //from www . j av a2 s . co m * @see Randomizer */ public void fillRandomData() { Field[] fields = getFields(); for (Field field : fields) { logger.debug("NAME :: " + field.getName()); if (!(Modifier.isFinal(field.getModifiers()))) { RandomizerTypes type = RandomizerTypes.MIXED; int len = 10; long min = 0, max = 0; String prefix = "", suffix = ""; String format = ""; String[] list = {}; Randomizer randomizer = field.getAnnotation(Randomizer.class); if (randomizer != null) { if (randomizer.skip()) { continue; } type = field.getType() == Date.class ? RandomizerTypes.DIGITS_ONLY : randomizer.type(); len = randomizer.length(); prefix = randomizer.prefix(); suffix = randomizer.suffix(); min = randomizer.minval(); max = min > randomizer.maxval() ? min : randomizer.maxval(); format = randomizer.format(); list = randomizer.dataset(); } else { // @Since 2.1.2 randomizer annotation is must for random // value // generation continue; } String str = ""; if ((list == null) || (list.length == 0)) { str = StringUtil.isBlank(format) ? RandomStringUtils.random(len, !type.equals(RandomizerTypes.DIGITS_ONLY), !type.equals(RandomizerTypes.LETTERS_ONLY)) : StringUtil.getRandomString(format); } else { str = getRandomValue(list); } try { // deal with IllegalAccessException field.setAccessible(true); Method setter = null; try { setter = this.getClass().getMethod("set" + StringUtil.getTitleCase(field.getName()), String.class); } catch (Exception e) { } if ((field.getType() == String.class) || (null != setter)) { if ((list == null) || (list.length == 0)) { if ((min == max) && (min == 0)) { str = StringUtil.isBlank(format) ? RandomStringUtils.random(len, !type.equals(RandomizerTypes.DIGITS_ONLY), !type.equals(RandomizerTypes.LETTERS_ONLY)) : StringUtil.getRandomString(format); } else { str = String.valueOf((int) (Math.random() * ((max - min) + 1)) + min); } } String rStr = prefix + str + suffix; if (null != setter) { setter.setAccessible(true); setter.invoke(this, rStr); } else { field.set(this, rStr); } } else { String rStr = ""; if ((min == max) && (min == 0)) { rStr = RandomStringUtils.random(len, false, true); } else { rStr = String.valueOf((int) (Math.random() * ((max - min) + 1)) + min); } if (field.getType() == Integer.TYPE) { field.setInt(this, Integer.parseInt(rStr)); } else if (field.getType() == Float.TYPE) { field.setFloat(this, Float.parseFloat(rStr)); } else if (field.getType() == Double.TYPE) { field.setDouble(this, Double.parseDouble(rStr)); } else if (field.getType() == Long.TYPE) { field.setLong(this, Long.parseLong(rStr)); } else if (field.getType() == Short.TYPE) { field.setShort(this, Short.parseShort(rStr)); } else if (field.getType() == Date.class) { logger.info("filling date " + rStr); int days = Integer.parseInt(rStr); field.set(this, DateUtil.getDate(days)); } else if (field.getType() == Boolean.TYPE) { field.setBoolean(this, RandomUtils.nextBoolean()); } } } catch (IllegalArgumentException e) { logger.error("Unable to fill random data in field " + field.getName(), e); } catch (IllegalAccessException e) { logger.error("Unable to Access " + field.getName(), e); } catch (InvocationTargetException e) { logger.error("Unable to Access setter for " + field.getName(), e); } } } }
From source file:net.dmulloy2.ultimatearena.types.ArenaZone.java
/** * {@inheritDoc}/* w w w. j a va 2 s .c o m*/ */ @Override public Map<String, Object> serialize() { Map<String, Object> data = new LinkedHashMap<>(); for (java.lang.reflect.Field field : ArenaZone.class.getDeclaredFields()) { if (Modifier.isTransient(field.getModifiers())) continue; try { boolean accessible = field.isAccessible(); field.setAccessible(true); if (field.getType().equals(Integer.TYPE)) { if (field.getInt(this) != 0) data.put(field.getName(), field.getInt(this)); } else if (field.getType().equals(Long.TYPE)) { if (field.getLong(this) != 0) data.put(field.getName(), field.getLong(this)); } else if (field.getType().equals(Boolean.TYPE)) { if (field.getBoolean(this)) data.put(field.getName(), field.getBoolean(this)); } else if (field.getType().isAssignableFrom(Collection.class)) { if (!((Collection<?>) field.get(this)).isEmpty()) data.put(field.getName(), field.get(this)); } else if (field.getType().isAssignableFrom(String.class)) { if ((String) field.get(this) != null) data.put(field.getName(), field.get(this)); } else if (field.getType().isAssignableFrom(Map.class)) { if (!((Map<?, ?>) field.get(this)).isEmpty()) data.put(field.getName(), field.get(this)); } else { if (field.get(this) != null) data.put(field.getName(), field.get(this)); } field.setAccessible(accessible); } catch (Throwable ex) { } } data.put("version", CURRENT_VERSION); return data; }
From source file:com.baidu.jprotobuf.pbrpc.spring.annotation.CommonAnnotationBeanPostProcessor.java
private InjectionMetadata findAnnotationMetadata(final Class clazz, final List<Class<? extends Annotation>> annotion) { // Quick check on the concurrent map first, with minimal locking. InjectionMetadata metadata = this.injectionMetadataCache.get(clazz); if (metadata == null) { synchronized (this.injectionMetadataCache) { metadata = this.injectionMetadataCache.get(clazz); if (metadata == null) { final InjectionMetadata newMetadata = new InjectionMetadata(clazz); ReflectionUtils.doWithFields(clazz, new ReflectionUtils.FieldCallback() { public void doWith(Field field) { for (Class<? extends Annotation> anno : annotion) { Annotation annotation = field.getAnnotation(anno); if (annotation != null) { if (Modifier.isStatic(field.getModifiers())) { throw new IllegalStateException( "Autowired annotation is not supported on static fields"); }// w w w .j av a 2 s.co m newMetadata.addInjectedField(new AutowiredFieldElement(field, annotation)); } } } }); ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() { public void doWith(Method method) { for (Class<? extends Annotation> anno : annotion) { Annotation annotation = method.getAnnotation(anno); if (annotation != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { if (Modifier.isStatic(method.getModifiers())) { throw new IllegalStateException( "Autowired annotation is not supported on static methods"); } if (method.getParameterTypes().length == 0) { throw new IllegalStateException( "Autowired annotation requires at least one argument: " + method); } PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method); newMetadata .addInjectedMethod(new AutowiredMethodElement(method, annotation, pd)); } } } }); metadata = newMetadata; this.injectionMetadataCache.put(clazz, metadata); } } } return metadata; }
From source file:com.dotweblabs.twirl.gae.GaeUnmarshaller.java
private void setFieldValue(Field field, Object instance, Object value) { boolean accessible = field.isAccessible(); Class<?> clazz = field.getType(); try {//w ww . ja va2 s . c o m if ((field.getModifiers() & java.lang.reflect.Modifier.FINAL) == java.lang.reflect.Modifier.FINAL) { // do nothing for a final field // usually static UID fields } else { if (field.getType().isPrimitive() && value == null) { Object defaultValue = PrimitiveDefaults.getDefaultValue(clazz); field.setAccessible(true); field.set(instance, defaultValue); field.setAccessible(accessible); } else { field.setAccessible(true); field.set(instance, value); field.setAccessible(accessible); } } } catch (IllegalAccessException e) { e.printStackTrace(); } }
From source file:org.makersoft.activesql.builder.GenericStatementBuilder.java
public GenericStatementBuilder(Configuration configuration, Class<?> entityClass) { super(configuration); this.entityClass = entityClass; String resource = entityClass.getName().replace('.', '/') + ".java (best guess)"; assistant = new MapperBuilderAssistant(configuration, resource); entity = entityClass.getAnnotation(Entity.class); mapperType = entity.mapper();//ww w . j ava 2 s.c o m if (!mapperType.isAssignableFrom(Void.class)) { namespace = mapperType.getName(); } else { namespace = entityClass.getName(); } assistant.setCurrentNamespace(namespace); databaseId = super.getConfiguration().getDatabaseId(); lang = super.getConfiguration().getDefaultScriptingLanuageInstance(); //~~~~~~~~~~~~~~~~~~~~~~~~~~~ Table table = entityClass.getAnnotation(Table.class); if (table == null) { tableName = CaseFormatUtils.camelToUnderScore(entityClass.getSimpleName()); } else { tableName = table.name(); } ///~~~~~~~~~~~~~~~~~~~~~~ idField = AnnotationUtils.findDeclaredFieldWithAnnoation(Id.class, entityClass); versionField = AnnotationUtils.findDeclaredFieldWithAnnoation(Version.class, entityClass); ReflectionUtils.doWithFields(entityClass, new FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { columnFields.add(field); } }, new FieldFilter() { @Override public boolean matches(Field field) { if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) { return false; } for (Annotation annotation : field.getAnnotations()) { if (Transient.class.isAssignableFrom(annotation.getClass()) || Id.class.isAssignableFrom(annotation.getClass())) { return false; } } return true; } }); }