List of usage examples for java.lang.reflect AccessibleObject setAccessible
@CallerSensitive public static void setAccessible(AccessibleObject[] array, boolean flag)
From source file:ObjectAnalyzerTest.java
/** * Converts an object to a string representation that lists all fields. * // ww w. j ava 2 s . co m * @param obj * an object * @return a string with the object's class name and all field names and * values */ public String toString(Object obj) { if (obj == null) return "null"; if (visited.contains(obj)) return "..."; visited.add(obj); Class cl = obj.getClass(); if (cl == String.class) return (String) obj; if (cl.isArray()) { String r = cl.getComponentType() + "[]{"; for (int i = 0; i < Array.getLength(obj); i++) { if (i > 0) r += ","; Object val = Array.get(obj, i); if (cl.getComponentType().isPrimitive()) r += val; else r += toString(val); } return r + "}"; } String r = cl.getName(); // inspect the fields of this class and all superclasses do { r += "["; Field[] fields = cl.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); // get the names and values of all fields for (Field f : fields) { if (!Modifier.isStatic(f.getModifiers())) { if (!r.endsWith("[")) r += ","; r += f.getName() + "="; try { Class t = f.getType(); Object val = f.get(obj); if (t.isPrimitive()) r += val; else r += toString(val); } catch (Exception e) { e.printStackTrace(); } } } r += "]"; cl = cl.getSuperclass(); } while (cl != null); return r; }
From source file:org.springmodules.cache.util.Reflections.java
/** * <p>//from ww w .j a va 2 s .c o m * This method uses reflection to build a valid hash code. * </p> * * <p> * It uses <code>AccessibleObject.setAccessible</code> to gain access to * private fields. This means that it will throw a security exception if run * under a security manager, if the permissions are not set up correctly. It * is also not as efficient as testing explicitly. * </p> * * <p> * Transient members will not be used, as they are likely derived fields, * and not part of the value of the <code>Object</code>. * </p> * * <p> * Static fields will not be tested. Superclass fields will be included. * </p> * * @param obj * the object to create a <code>hashCode</code> for * @return the generated hash code, or zero if the given object is * <code>null</code> */ public static int reflectionHashCode(Object obj) { if (obj == null) return 0; Class targetClass = obj.getClass(); if (Objects.isArrayOfPrimitives(obj) || Objects.isPrimitiveOrWrapper(targetClass)) { return Objects.nullSafeHashCode(obj); } if (targetClass.isArray()) { return reflectionHashCode((Object[]) obj); } if (obj instanceof Collection) { return reflectionHashCode((Collection) obj); } if (obj instanceof Map) { return reflectionHashCode((Map) obj); } // determine whether the object's class declares hashCode() or has a // superClass other than java.lang.Object that declares hashCode() Class clazz = (obj instanceof Class) ? (Class) obj : obj.getClass(); Method hashCodeMethod = ReflectionUtils.findMethod(clazz, "hashCode", new Class[0]); if (hashCodeMethod != null) { return obj.hashCode(); } // could not find a hashCode other than the one declared by java.lang.Object int hash = INITIAL_HASH; try { while (targetClass != null) { Field[] fields = targetClass.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; int modifiers = field.getModifiers(); if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) { hash = MULTIPLIER * hash + reflectionHashCode(field.get(obj)); } } targetClass = targetClass.getSuperclass(); } } catch (IllegalAccessException exception) { // ///CLOVER:OFF ReflectionUtils.handleReflectionException(exception); // ///CLOVER:ON } return hash; }
From source file:com.gisgraphy.webapp.taglib.ConstantsTei.java
/** * Return information about the scripting variables to be created. * /*from w ww .j a va 2s .c om*/ * @param data * the input data * @return VariableInfo array of variable information */ @Override public VariableInfo[] getVariableInfo(TagData data) { // loop through and expose all attributes List<VariableInfo> vars = new ArrayList<VariableInfo>(); try { String clazz = data.getAttributeString("className"); if (clazz == null) { clazz = Constants.class.getName(); } Class<?> c = Class.forName(clazz); // if no var specified, get all if (data.getAttributeString("var") == null) { Field[] fields = c.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (Field field : fields) { String type = field.getType().getName(); vars.add(new VariableInfo(field.getName(), ((field.getType().isArray()) ? type.substring(2, type.length() - 1) + "[]" : type), true, VariableInfo.AT_END)); } } else { String var = data.getAttributeString("var"); String type = c.getField(var).getType().getName(); vars.add(new VariableInfo(c.getField(var).getName(), ((c.getField(var).getType().isArray()) ? type.substring(2, type.length() - 1) + "[]" : type), true, VariableInfo.AT_END)); } } catch (Exception cnf) { log.error(cnf.getMessage()); } return vars.toArray(new VariableInfo[] {}); }
From source file:com.sonatype.security.ldap.api.DeepEqualsBuilder.java
private static void reflectionAppend(Object lhs, Object rhs, Class clazz, EqualsBuilder builder, boolean useTransients, String[] excludeFields) { while (clazz.getSuperclass() != null) { Field[] fields = clazz.getDeclaredFields(); List excludedFieldList = excludeFields != null ? Arrays.asList(excludeFields) : Collections.EMPTY_LIST; AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length && builder.isEquals(); i++) { Field f = fields[i];//w w w.ja v a 2 s . c om if (!excludedFieldList.contains(f.getName()) && (f.getName().indexOf('$') == -1) && (useTransients || !Modifier.isTransient(f.getModifiers())) && (!Modifier.isStatic(f.getModifiers()))) { try { Object lhsChild = f.get(lhs); Object rhsChild = f.get(rhs); Class testClass = getTestClass(lhsChild, rhsChild); boolean hasEqualsMethod = classHasEqualsMethod(testClass); if (testClass != null && !hasEqualsMethod) { reflectionAppend(lhsChild, rhsChild, testClass, builder, useTransients, excludeFields); } else { builder.append(lhsChild, rhsChild); } } catch (IllegalAccessException e) { // this can't happen. Would get a Security exception instead // throw a runtime exception in case the impossible happens. throw new InternalError("Unexpected IllegalAccessException"); } } } // now for the parent clazz = clazz.getSuperclass(); reflectionAppend(lhs, rhs, clazz, builder, useTransients, excludeFields); } }
From source file:alpha.portal.webapp.taglib.ConstantsTei.java
/** * Return information about the scripting variables to be created. * //from ww w . j a v a 2 s. co m * @param data * the input data * @return VariableInfo array of variable information */ @Override public VariableInfo[] getVariableInfo(final TagData data) { // loop through and expose all attributes final List<VariableInfo> vars = new ArrayList<VariableInfo>(); try { String clazz = data.getAttributeString("className"); if (clazz == null) { clazz = Constants.class.getName(); } final Class c = Class.forName(clazz); // if no var specified, get all if (data.getAttributeString("var") == null) { final Field[] fields = c.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (final Field field : fields) { final String type = field.getType().getName(); vars.add(new VariableInfo(field.getName(), ((field.getType().isArray()) ? type.substring(2, type.length() - 1) + "[]" : type), true, VariableInfo.AT_END)); } } else { final String var = data.getAttributeString("var"); final String type = c.getField(var).getType().getName(); vars.add(new VariableInfo(c.getField(var).getName(), ((c.getField(var).getType().isArray()) ? type.substring(2, type.length() - 1) + "[]" : type), true, VariableInfo.AT_END)); } } catch (final Exception cnf) { this.log.error(cnf.getMessage()); cnf.printStackTrace(); } return vars.toArray(new VariableInfo[] {}); }
From source file:com.gisgraphy.webapp.taglib.ConstantsTag.java
/** * Main method that does processing and exposes Constants in specified scope * //from w ww .ja v a 2 s . com * @return int * @throws JspException * if processing fails */ @Override public int doStartTag() throws JspException { // Using reflection, get the available field names in the class Class<?> c = null; int toScope = PageContext.PAGE_SCOPE; if (scope != null) { toScope = getScope(scope); } try { c = Class.forName(clazz); } catch (ClassNotFoundException cnf) { log.error("ClassNotFound - maybe a typo?"); throw new JspException(cnf.getMessage()); } try { // if var is null, expose all variables if (var == null) { Field[] fields = c.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (Field field : fields) { pageContext.setAttribute(field.getName(), field.get(this), toScope); } } else { try { Object value = c.getField(var).get(this); pageContext.setAttribute(c.getField(var).getName(), value, toScope); } catch (NoSuchFieldException nsf) { log.error(nsf.getMessage()); throw new JspException(nsf); } } } catch (IllegalAccessException iae) { log.error("Illegal Access Exception - maybe a classloader issue?"); throw new JspException(iae); } // Continue processing this page return (SKIP_BODY); }
From source file:alpha.portal.webapp.taglib.ConstantsTag.java
/** * Main method that does processing and exposes Constants in specified * scope.// w ww.j a va2 s . com * * @return int * @throws JspException * if processing fails */ @Override public int doStartTag() throws JspException { // Using reflection, get the available field names in the class Class c = null; int toScope = PageContext.PAGE_SCOPE; if (this.scope != null) { toScope = this.getScope(this.scope); } try { c = Class.forName(this.clazz); } catch (final ClassNotFoundException cnf) { this.log.error("ClassNotFound - maybe a typo?"); throw new JspException(cnf.getMessage()); } try { // if var is null, expose all variables if (this.var == null) { final Field[] fields = c.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (final Field field : fields) { this.pageContext.setAttribute(field.getName(), field.get(this), toScope); } } else { try { final Object value = c.getField(this.var).get(this); this.pageContext.setAttribute(c.getField(this.var).getName(), value, toScope); } catch (final NoSuchFieldException nsf) { this.log.error(nsf.getMessage()); throw new JspException(nsf); } } } catch (final IllegalAccessException iae) { this.log.error("Illegal Access Exception - maybe a classloader issue?"); throw new JspException(iae); } // Continue processing this page return (Tag.SKIP_BODY); }
From source file:HashCodeAssist.java
/** * <p>//from w w w.j a va2 s . c o m * Appends the fields and values defined by the given object of the given * <code>Class</code>. * </p> * * @param object * the object to append details of * @param clazz * the class to append details of * @param builder * the builder to append to * @param useTransients * whether to use transient fields * @param excludeFields * Collection of String field names to exclude from use in * calculation of hash code */ private static void reflectionAppend(Object object, Class<?> clazz, HashCodeAssist builder, boolean useTransients, String... excludeFields) { if (isRegistered(object)) { return; } try { register(object); Field[] fields = clazz.getDeclaredFields(); List<String> excludedFieldList = excludeFields != null ? Arrays.asList(excludeFields) : Collections.EMPTY_LIST; AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (!excludedFieldList.contains(field.getName()) && (field.getName().indexOf('$') == -1) && (useTransients || !Modifier.isTransient(field.getModifiers())) && (!Modifier.isStatic(field.getModifiers()))) { try { Object fieldValue = field.get(object); builder.append(fieldValue); } catch (IllegalAccessException e) { // this can't happen. Would get a Security exception // instead // throw a runtime exception in case the impossible // happens. throw new InternalError("Unexpected IllegalAccessException"); } } } } finally { unregister(object); } }
From source file:au.com.dw.testdatacapturej.reflection.MetadataGenerationHandler.java
/** * Use reflection to process the fields in an object. Iterates through the fields in the object * and passes them to the appropriate handlers. * //w ww . j ava 2 s.c om * Note: does not handle static fields yet. * * @param object * @throws IllegalArgumentException * @throws IllegalAccessException */ protected void handleFields(ObjectInfo info) throws IllegalArgumentException, IllegalAccessException { // use reflection to get the fields of the class Object object = info.getValue(); Class<?> clazz = object.getClass(); Field[] fields = clazz.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); // check configuration for non-standard handling ConfigUtil configUtil = new ConfigUtil(); // get list of field names that have been configured to have non-standard setter method generation List<String> ignoredSetterFieldNames = configUtil.getIgnoredSetters(info); // get list of collection field names for collection that are only accessed through adder methods List<CollectionAdderConfig> collectionConfigs = configUtil.getAddedCollections(info); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; int mod = field.getModifiers(); // ignore static fields if (!Modifier.isStatic(mod)) { // get the field info String fieldName = field.getName(); Object fieldValue = field.get(object); // create new ObjectInfo for the field object ObjectInfo fieldInfo = new ObjectInfo(); fieldInfo.setFieldName(fieldName); fieldInfo.setValue(fieldValue); fieldInfo.setContainingClassFieldName(info.getClassFieldName()); fieldInfo.getConstructorInfo().setHasDefaultConstructor(hasDefaultConstructor(fieldValue)); // check if requires any special setter method generation if (ignoredSetterFieldNames != null) { if (ignoredSetterFieldNames.contains(fieldName)) { fieldInfo.getSetterAdderInfo().setSetterGenerationType(SetterGenerationType.IGNORE); } } // determine type of field and pass to handler if (fieldValue != null) { if (!ReflectionUtil.hasSetterMethod(object, fieldName, fieldValue)) { fieldInfo.getSetterAdderInfo().setHasSetter(false); } if (TypeUtil.isJavaClass(fieldValue)) { fieldInfo.setType(ObjectType.SIMPLE); fieldInfo.setClassName(fieldValue.getClass().getName()); fieldInfo.setClassFieldName(BuilderUtil.createClassFieldName(fieldValue, null, null)); } else if (TypeUtil.isArray(fieldValue)) { fieldInfo.setType(ObjectType.ARRAY); // special handling for array class names fieldInfo.setClassName(ReflectionUtil.getArrayClassName(fieldValue)); String arrayType = fieldValue.getClass().getComponentType().getName(); fieldInfo.setClassFieldName(BuilderUtil.createArrayClassFieldName(arrayType, null, null)); if (!fieldInfo.isSetterIgnoreType()) { handleArray(fieldInfo); } } else if (TypeUtil.isCollection(fieldValue)) { fieldInfo.setType(ObjectType.COLLECTION); fieldInfo.setClassName(fieldValue.getClass().getName()); fieldInfo.setClassFieldName(BuilderUtil.createClassFieldName(fieldValue, null, null)); // check if the collection field is only accessed through adder methods // Note: the adder check overrides the ignored setter check if both are set CollectionAdderConfig foundConfig = configUtil.getCollectionAdderConfig(collectionConfigs, fieldName); if (foundConfig != null) { fieldInfo.getSetterAdderInfo().setUsesAdder(true); fieldInfo.getSetterAdderInfo().setAdderMethodName(foundConfig.getAdderMethodName()); handleCollection(fieldInfo); } else if (!fieldInfo.isSetterIgnoreType()) { handleCollection(fieldInfo); } } else if (TypeUtil.isMap(fieldValue)) { fieldInfo.setType(ObjectType.MAP); fieldInfo.setClassName(fieldValue.getClass().getName()); fieldInfo.setClassFieldName(BuilderUtil.createClassFieldName(fieldValue, null, null)); if (!fieldInfo.isSetterIgnoreType()) { handleMap(fieldInfo); } } else { fieldInfo.setType(ObjectType.OBJECT); fieldInfo.setClassName(fieldValue.getClass().getName()); fieldInfo.setClassFieldName(BuilderUtil.createClassFieldName(fieldValue, null, null)); if (!fieldInfo.isSetterIgnoreType()) { handleFields(fieldInfo); } } } else { // get class name from the Field if the field value is null fieldInfo.setClassName(ReflectionUtil.getClassNameFromField(field)); fieldInfo.setClassFieldName(BuilderUtil.createClassFieldName(field, null, null)); fieldInfo.setType(ObjectType.SIMPLE); } // check if configured parameterized constructor is to be used for the field fieldInfo.getConstructorInfo() .addConstructorParamFieldNames(configUtil.getConstructionParameters(fieldInfo)); // add the parent class to field class link fieldInfo.setParentInfo(info); info.addFieldToList(fieldInfo); } } }
From source file:com.gwtcx.server.servlet.FileUploadServlet.java
@SuppressWarnings("rawtypes") private void importCsvFile(String recordType, String filename) { try {/* www.j a v a2 s. c om*/ // get the Class object for this recordType's DAO Class dao = getEntityDao(recordType); Object daoObject = createEntityDao(dao); // get the Class object for this recordType Class entity = getEntity(recordType); Field[] fields = entity.getDeclaredFields(); // allow access to the Entities fields AccessibleObject.setAccessible(fields, true); // initialise the CSV Reader CSVReader reader = new CSVReader(new FileReader(filename)); String[] nextLine; // process the first line in the file if ((nextLine = reader.readNext()) != null) { // build the HashMap of Field names getFieldNames(nextLine); } // process the file a line at a time while ((nextLine = reader.readNext()) != null) { persistEntity(daoObject, createEntity(entity, fields, nextLine)); } } catch (ClassNotFoundException e) { Log.error("Error encountered while looking for class", e); } catch (FileNotFoundException e) { Log.error("Error encountered while reading file", e); } catch (Exception e) { Log.error("Error encountered while importing file", e); } }