List of usage examples for java.lang.reflect Field getModifiers
public int getModifiers()
From source file:com.trafficspaces.api.model.Resource.java
public void setJSONObject(JSONObject jsonObject) { Iterator itr = jsonObject.keys(); while (itr.hasNext()) { String key = (String) itr.next(); Object value = jsonObject.opt(key); try {// w ww . j a v a 2s . c o m Field field = this.getClass().getField(key); Class type = field.getType(); int fieldModifiers = field.getModifiers(); //System.out.println("key=" + key + ", name=" + field.getName() + ", value=" + value + ", type=" +type + ", componentType=" +type.getComponentType() + // ", ispublic="+Modifier.isPublic(fieldModifiers) + ", isstatic="+Modifier.isStatic(fieldModifiers) + ", isnative="+Modifier.isNative(fieldModifiers) + // ", isprimitive="+type.isPrimitive() + ", isarray="+type.isArray() + ", isResource="+Resource.class.isAssignableFrom(type)); if (type.isPrimitive()) { if (type.equals(int.class)) { field.setInt(this, jsonObject.getInt(key)); } else if (type.equals(double.class)) { field.setDouble(this, jsonObject.getDouble(key)); } } else if (type.isArray()) { JSONArray jsonArray = null; if (value instanceof JSONArray) { jsonArray = (JSONArray) value; } else if (value instanceof JSONObject) { JSONObject jsonSubObject = (JSONObject) value; jsonArray = jsonSubObject.optJSONArray(key.substring(0, key.length() - 1)); } if (jsonArray != null && jsonArray.length() > 0) { Class componentType = type.getComponentType(); Object[] values = (Object[]) Array.newInstance(componentType, jsonArray.length()); for (int j = 0; j < jsonArray.length(); j++) { Resource resource = (Resource) componentType.newInstance(); resource.setJSONObject(jsonArray.getJSONObject(j)); values[j] = resource; } field.set(this, values); } } else if (Resource.class.isAssignableFrom(type) && value instanceof JSONObject) { Resource resource = (Resource) type.newInstance(); resource.setJSONObject((JSONObject) value); field.set(this, resource); } else if (type.equals(String.class) && value instanceof String) { field.set(this, (String) value); } } catch (NoSuchFieldException nsfe) { System.err.println("warning: field does not exist. key=" + key + ",value=" + value); } catch (Exception e) { e.printStackTrace(); System.err.println("error: key=" + key + ",value=" + value + ", error=" + e.getMessage()); } } }
From source file:org.apache.niolex.commons.reflect.FieldFilter.java
/** * Filter the fields with only static fields. * * @return this//w w w. j a v a 2s . co m */ public final FieldFilter<FT> onlyStatic() { return this.add(new Filter() { @Override public boolean isValid(Field f) { return Modifier.isStatic(f.getModifiers()); } }); }
From source file:org.apache.niolex.commons.reflect.FieldFilter.java
/** * Filter the fields without static fields. * * @return this/*from www. j ava 2s. c o m*/ */ public final FieldFilter<FT> noStatic() { return this.add(new Filter() { @Override public boolean isValid(Field f) { return !Modifier.isStatic(f.getModifiers()); } }); }
From source file:io.fabric8.cxf.endpoint.IgnorePropertiesBackedByTransientFields.java
/** * Returns false if the getter method has a field of the same name which is transient * @return// ww w.j a va 2 s .c o m */ protected boolean isGetterMethodWithFieldVisible(Object method, String fieldName, Class<?> declaringClass) { Field field = findField(fieldName, declaringClass); if (field != null) { int fieldModifiers = field.getModifiers(); if (Modifier.isTransient(fieldModifiers)) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Ignoring getter " + method + " due to transient field called " + fieldName); } return false; } } return true; }
From source file:org.apache.syncope.client.console.panels.AnyTypesPanel.java
@Override protected List<IColumn<AnyTypeTO, String>> getColumns() { final List<IColumn<AnyTypeTO, String>> columns = new ArrayList<>(); for (Field field : AnyTypeTO.class.getDeclaredFields()) { if (field != null && !Modifier.isStatic(field.getModifiers())) { final String fieldName = field.getName(); if (field.getType().isArray() || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())) { columns.add(new PropertyColumn<>(new ResourceModel(field.getName()), field.getName())); } else if (field.getType().equals(boolean.class) || field.getType().equals(Boolean.class)) { columns.add(new BooleanPropertyColumn<>(new ResourceModel(field.getName()), field.getName(), field.getName())); } else { columns.add(new PropertyColumn<AnyTypeTO, String>(new ResourceModel(field.getName()), field.getName(), field.getName()) { private static final long serialVersionUID = -6902459669035442212L; @Override/*w w w . ja v a 2s .com*/ public String getCssClass() { String css = super.getCssClass(); if ("key".equals(fieldName)) { css = StringUtils.isBlank(css) ? "col-xs-1" : css + " col-xs-1"; } return css; } }); } } } return columns; }
From source file:org.apache.syncope.client.console.panels.AnyTypeClassesPanel.java
@Override protected List<IColumn<AnyTypeClassTO, String>> getColumns() { final List<IColumn<AnyTypeClassTO, String>> columns = new ArrayList<>(); for (Field field : AnyTypeClassTO.class.getDeclaredFields()) { if (field != null && !Modifier.isStatic(field.getModifiers())) { final String fieldName = field.getName(); if (field.getType().isArray() || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())) { columns.add(new PropertyColumn<>(new ResourceModel(field.getName()), field.getName())); } else if (field.getType().equals(boolean.class) || field.getType().equals(Boolean.class)) { columns.add(new BooleanPropertyColumn<>(new ResourceModel(field.getName()), field.getName(), field.getName())); } else { columns.add(new PropertyColumn<AnyTypeClassTO, String>(new ResourceModel(field.getName()), field.getName(), field.getName()) { private static final long serialVersionUID = -6902459669035442212L; @Override//from w ww . j a v a 2 s . c o m public String getCssClass() { String css = super.getCssClass(); if ("key".equals(fieldName)) { css = StringUtils.isBlank(css) ? "col-xs-1" : css + " col-xs-1"; } return css; } }); } } } return columns; }
From source file:kenh.xscript.elements.Debug.java
private void list(JList c) { if (result == null) return;// w ww . j av a2s .c o m if (StringUtils.isBlank(c.getSelectedValue().toString())) return; if (this.getEnvironment() != null) { String context = ""; try { Object obj = this.getEnvironment().getVariable(c.getSelectedValue().toString()); if (obj != null) { context = c.getSelectedValue().toString() + LINE_SEP + LINE_SEP; context += "-- Class: " + obj.getClass().getCanonicalName() + LINE_SEP; context += LINE_SEP; context += "-- Fields: " + LINE_SEP; Field[] fields = obj.getClass().getFields(); for (Field field : fields) { int i = field.getModifiers(); String retval = Modifier.toString(i); if (StringUtils.contains(retval, "public")) { context += "\t" + field.getName() + " - " + retval + LINE_SEP; } } context += LINE_SEP; context += "-- Method: " + LINE_SEP; java.lang.reflect.Method[] methods = obj.getClass().getMethods(); for (java.lang.reflect.Method method : methods) { int i = method.getModifiers(); String retval = Modifier.toString(i); if (StringUtils.contains(retval, "public")) { Class[] pcs = method.getParameterTypes(); StringBuffer sb = new StringBuffer(); for (Class c_ : pcs) { String s = c_.getSimpleName(); sb.append(s + ", "); } String p = StringUtils.trimToEmpty(StringUtils.substringBeforeLast(sb.toString(), ",")); context += "\t" + method.getName() + "(" + p + ") - " + retval + LINE_SEP; } } } else { context = "<null>"; } } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); context = sw.toString(); } result.setText(context); } else { result.setText(c.getSelectedValue().toString()); } result.setCaretPosition(0); c.requestFocus(); }
From source file:ch.rasc.extclassgenerator.ModelGenerator.java
public static ModelBean createModel(final Class<?> clazz, final OutputConfig outputConfig) { Assert.notNull(clazz, "clazz must not be null"); Assert.notNull(outputConfig.getIncludeValidation(), "includeValidation must not be null"); ModelCacheKey key = new ModelCacheKey(clazz.getName(), outputConfig); SoftReference<ModelBean> modelReference = modelCache.get(key); if (modelReference != null && modelReference.get() != null) { return modelReference.get(); }/*from w w w . j a v a 2 s . c o m*/ Model modelAnnotation = clazz.getAnnotation(Model.class); final ModelBean model = new ModelBean(); if (modelAnnotation != null && StringUtils.hasText(modelAnnotation.value())) { model.setName(modelAnnotation.value()); } else { model.setName(clazz.getName()); } if (modelAnnotation != null) { model.setAutodetectTypes(modelAnnotation.autodetectTypes()); } if (modelAnnotation != null) { model.setExtend(modelAnnotation.extend()); model.setIdProperty(modelAnnotation.idProperty()); model.setVersionProperty(trimToNull(modelAnnotation.versionProperty())); model.setPaging(modelAnnotation.paging()); model.setDisablePagingParameters(modelAnnotation.disablePagingParameters()); model.setCreateMethod(trimToNull(modelAnnotation.createMethod())); model.setReadMethod(trimToNull(modelAnnotation.readMethod())); model.setUpdateMethod(trimToNull(modelAnnotation.updateMethod())); model.setDestroyMethod(trimToNull(modelAnnotation.destroyMethod())); model.setMessageProperty(trimToNull(modelAnnotation.messageProperty())); model.setWriter(trimToNull(modelAnnotation.writer())); model.setReader(trimToNull(modelAnnotation.reader())); model.setSuccessProperty(trimToNull(modelAnnotation.successProperty())); model.setTotalProperty(trimToNull(modelAnnotation.totalProperty())); model.setRootProperty(trimToNull(modelAnnotation.rootProperty())); model.setWriteAllFields(modelAnnotation.writeAllFields()); model.setIdentifier(trimToNull(modelAnnotation.identifier())); String clientIdProperty = trimToNull(modelAnnotation.clientIdProperty()); if (StringUtils.hasText(clientIdProperty)) { model.setClientIdProperty(clientIdProperty); model.setClientIdPropertyAddToWriter(true); } else { model.setClientIdProperty(null); model.setClientIdPropertyAddToWriter(false); } } final Set<String> hasReadMethod = new HashSet<String>(); BeanInfo bi; try { bi = Introspector.getBeanInfo(clazz); } catch (IntrospectionException e) { throw new RuntimeException(e); } for (PropertyDescriptor pd : bi.getPropertyDescriptors()) { if (pd.getReadMethod() != null && pd.getReadMethod().getAnnotation(JsonIgnore.class) == null) { hasReadMethod.add(pd.getName()); } } if (clazz.isInterface()) { final List<Method> methods = new ArrayList<Method>(); ReflectionUtils.doWithMethods(clazz, new MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { methods.add(method); } }); Collections.sort(methods, new Comparator<Method>() { @Override public int compare(Method o1, Method o2) { return o1.getName().compareTo(o2.getName()); } }); for (Method method : methods) { createModelBean(model, method, outputConfig); } } else { final Set<String> fields = new HashSet<String>(); Set<ModelField> modelFieldsOnType = AnnotationUtils.getRepeatableAnnotation(clazz, ModelFields.class, ModelField.class); for (ModelField modelField : modelFieldsOnType) { if (StringUtils.hasText(modelField.value())) { ModelFieldBean modelFieldBean; if (StringUtils.hasText(modelField.customType())) { modelFieldBean = new ModelFieldBean(modelField.value(), modelField.customType()); } else { modelFieldBean = new ModelFieldBean(modelField.value(), modelField.type()); } updateModelFieldBean(modelFieldBean, modelField); model.addField(modelFieldBean); } } Set<ModelAssociation> modelAssociationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz, ModelAssociations.class, ModelAssociation.class); for (ModelAssociation modelAssociationAnnotation : modelAssociationsOnType) { AbstractAssociation modelAssociation = AbstractAssociation .createAssociation(modelAssociationAnnotation); if (modelAssociation != null) { model.addAssociation(modelAssociation); } } Set<ModelValidation> modelValidationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz, ModelValidations.class, ModelValidation.class); for (ModelValidation modelValidationAnnotation : modelValidationsOnType) { AbstractValidation modelValidation = AbstractValidation.createValidation( modelValidationAnnotation.propertyName(), modelValidationAnnotation, outputConfig.getIncludeValidation()); if (modelValidation != null) { model.addValidation(modelValidation); } } ReflectionUtils.doWithFields(clazz, new FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { if (!fields.contains(field.getName()) && (field.getAnnotation(ModelField.class) != null || field.getAnnotation(ModelAssociation.class) != null || (Modifier.isPublic(field.getModifiers()) || hasReadMethod.contains(field.getName())) && field.getAnnotation(JsonIgnore.class) == null)) { // ignore superclass declarations of fields already // found in a subclass fields.add(field.getName()); createModelBean(model, field, outputConfig); } } }); } modelCache.put(key, new SoftReference<ModelBean>(model)); return model; }
From source file:com.github.jiahut.demo.utils.LoggerPostProcessor.java
@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { List<Field> fields = Arrays.asList(bean.getClass().getDeclaredFields()); for (Field field : fields) { if (Logger.class.isAssignableFrom(field.getType()) && field.getAnnotation(InjectLogger.class) != null) { logger.debug("Attempting to inject a SLF4J logger on bean: " + bean.getClass()); if (field != null && (field.getModifiers() & Modifier.STATIC) == 0) { field.setAccessible(true); try { field.set(bean, LoggerFactory.getLogger(bean.getClass())); logger.debug("Successfully injected a SLF4J logger on bean: " + bean.getClass()); } catch (IllegalArgumentException e) { logger.warn("Could not inject logger for class: " + bean.getClass(), e); } catch (IllegalAccessException e) { logger.warn("Could not inject logger for class: " + bean.getClass(), e); }/*ww w . ja v a 2 s .co m*/ } } } return bean; }
From source file:de.micromata.genome.util.bean.PrivateBeanUtils.java
/** * Gets the bean size intern./*from w w w. j a v a2 s . c om*/ * * @param bean the bean * @param clazz the clazz * @param m the m * @param classNameMatcher the class name matcher * @param fieldNameMatcher the field name matcher * @return the bean size intern */ public static int getBeanSizeIntern(Object bean, Class<?> clazz, IdentityHashMap<Object, Object> m, Matcher<String> classNameMatcher, Matcher<String> fieldNameMatcher) { if (classNameMatcher.match(clazz.getName()) == false) { return 0; } if (clazz.isArray() == true) { if (clazz == boolean[].class) { return (((boolean[]) bean).length * 4); } else if (clazz == char[].class) { return (((char[]) bean).length * 2); } else if (clazz == byte[].class) { return (((byte[]) bean).length * 1); } else if (clazz == short[].class) { return (((short[]) bean).length * 2); } else if (clazz == int[].class) { return (((int[]) bean).length * 4); } else if (clazz == long[].class) { return (((long[]) bean).length * 4); } else if (clazz == float[].class) { return (((float[]) bean).length * 4); } else if (clazz == double[].class) { return (((double[]) bean).length * 8); } else { int length = Array.getLength(bean); int ret = (length * 4); for (int i = 0; i < length; ++i) { ret += getBeanSize(Array.get(bean, i), m, classNameMatcher, fieldNameMatcher); } return ret; } } int ret = 0; try { for (Field f : clazz.getDeclaredFields()) { int mod = f.getModifiers(); if (Modifier.isStatic(mod) == true) { continue; } if (fieldNameMatcher.match(clazz.getName() + "." + f.getName()) == false) { continue; } if (f.getType() == Boolean.TYPE) { ret += 4; } else if (f.getType() == Character.TYPE) { ret += 2; } else if (f.getType() == Byte.TYPE) { ret += 1; } else if (f.getType() == Short.TYPE) { ret += 2; } else if (f.getType() == Integer.TYPE) { ret += 4; } else if (f.getType() == Long.TYPE) { ret += 8; } else if (f.getType() == Float.TYPE) { ret += 4; } else if (f.getType() == Double.TYPE) { ret += 8; } else { ret += 4; Object o = null; try { o = readField(bean, f); if (o == null) { continue; } } catch (NoClassDefFoundError ex) { // nothing continue; } int nestedsize = getBeanSize(o, o.getClass(), m, classNameMatcher, fieldNameMatcher); ret += nestedsize; } } } catch (NoClassDefFoundError ex) { // ignore here. } if (clazz == Object.class || clazz.getSuperclass() == null) { return ret; } ret += getBeanSizeIntern(bean, clazz.getSuperclass(), m, classNameMatcher, fieldNameMatcher); return ret; }