Java Code Examples for java.lang.reflect.AccessibleObject

The following are top voted examples for showing how to use java.lang.reflect.AccessibleObject. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: feeyo-redisproxy   File: ReflectUtil.java   View source code 6 votes vote down vote up
/**
 * 放回一个可以访问的字段或者方法
 *
 */
public static <T extends AccessibleObject> T setAndGetAccessible(T accessible) {
	if (accessible == null) {
		return null;
	}

	if (accessible instanceof Member) {
		Member member = (Member) accessible;

		if (Modifier.isPublic(member.getModifiers())
				&& Modifier.isPublic(member.getDeclaringClass().getModifiers())) {

			return accessible;
		}
	}

	if (!accessible.isAccessible()) {
		accessible.setAccessible(true);
	}

	return accessible;
}
 
Example 2
Project: DroidTelescope   File: MemberUtils.java   View source code 6 votes vote down vote up
static boolean setAccessibleWorkaround(final AccessibleObject o) {
    if (o == null || o.isAccessible()) {
        return false;
    }
    final Member m = (Member) o;
    if (!o.isAccessible() && Modifier.isPublic(m.getModifiers()) && isPackageAccess(m
            .getDeclaringClass().getModifiers())) {
        try {
            o.setAccessible(true);
            return true;
        } catch (final SecurityException e) { // NOPMD
            // ignore in favor of subsequent IllegalAccessException
        }
    }
    return false;
}
 
Example 3
Project: Equella   File: WizardControl.java   View source code 6 votes vote down vote up
protected void cloneFields(Class<? extends WizardControl> clazz, WizardControl control)
{
	Field[] declaredFields = clazz.getDeclaredFields();
	AccessibleObject.setAccessible(declaredFields, true);
	for( Field field : declaredFields )
	{
		try
		{
			if( (field.getModifiers() & (Modifier.STATIC | Modifier.FINAL)) == 0 )
			{
				field.set(control, field.get(this));
			}
		}
		catch( Exception e )
		{
			throw new RuntimeException(e);
		}
	}
}
 
Example 4
Project: lams   File: EqualsBuilder.java   View source code 6 votes vote down vote up
/**
 * <p>Appends the fields and values defined by the given object of the
 * given Class.</p>
 * 
 * @param lhs  the left hand object
 * @param rhs  the right hand object
 * @param clazz  the class to append details of
 * @param builder  the builder to append to
 * @param useTransients  whether to test transient fields
 * @param excludeFields  array of field names to exclude from testing
 */
private static void reflectionAppend(
    Object lhs,
    Object rhs,
    Class clazz,
    EqualsBuilder builder,
    boolean useTransients,
    String[] excludeFields) {
    Field[] fields = clazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    for (int i = 0; i < fields.length && builder.isEquals; i++) {
        Field f = fields[i];
        if (!ArrayUtils.contains(excludeFields, f.getName())
            && (f.getName().indexOf('$') == -1)
            && (useTransients || !Modifier.isTransient(f.getModifiers()))
            && (!Modifier.isStatic(f.getModifiers()))) {
            try {
                builder.append(f.get(lhs), f.get(rhs));
            } 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");
            }
        }
    }
}
 
Example 5
Project: lams   File: SimpleClassLoadHelper.java   View source code 6 votes vote down vote up
/**
 * Enable sharing of the class-loader with 3rd party.
 *
 * @return the class-loader user be the helper.
 */
public ClassLoader getClassLoader() {
    // To follow the same behavior of Class.forName(...) I had to play
    // dirty (Supported by Sun, IBM & BEA JVMs)
    try {
        // Get a reference to this class' class-loader
        ClassLoader cl = this.getClass().getClassLoader();
        // Create a method instance representing the protected
        // getCallerClassLoader method of class ClassLoader
        Method mthd = ClassLoader.class.getDeclaredMethod(
                "getCallerClassLoader", new Class<?>[0]);
        // Make the method accessible.
        AccessibleObject.setAccessible(new AccessibleObject[] {mthd}, true);
        // Try to get the caller's class-loader
        return (ClassLoader)mthd.invoke(cl, new Object[0]);
    } catch (Throwable all) {
        // Use this class' class-loader
        return this.getClass().getClassLoader();
    }
}
 
Example 6
Project: asura   File: SimpleClassLoadHelper.java   View source code 6 votes vote down vote up
/**
 * Enable sharing of the class-loader with 3rd party.
 *
 * @return the class-loader user be the helper.
 */
public ClassLoader getClassLoader() {
    // To follow the same behavior of Class.forName(...) I had to play
    // dirty (Supported by Sun, IBM & BEA JVMs)
    try {
        // Get a reference to this class' class-loader
        ClassLoader cl = this.getClass().getClassLoader();
        // Create a method instance representing the protected
        // getCallerClassLoader method of class ClassLoader
        Method mthd = ClassLoader.class.getDeclaredMethod(
                "getCallerClassLoader", new Class[0]);
        // Make the method accessible.
        AccessibleObject.setAccessible(new AccessibleObject[] {mthd}, true);
        // Try to get the caller's class-loader
        return (ClassLoader)mthd.invoke(cl, new Object[0]);
    } catch (Exception all) {
        // Use this class' class-loader
        return this.getClass().getClassLoader();
    }
}
 
Example 7
Project: openjdk-jdk10   File: PublicSuper.java   View source code 6 votes vote down vote up
public static void checkAccess(AccessibleObject accessibleObject, Object obj)
    throws IllegalAccessException,
           InvocationTargetException,
           InstantiationException
{
    if (accessibleObject instanceof Field) {
        Field field = (Field) accessibleObject;
        field.set(obj, 42);
        field.get(obj);
    } else if (accessibleObject instanceof Method) {
        Method method = (Method) accessibleObject;
        method.invoke(obj);
    } else if (accessibleObject instanceof Constructor) {
        Constructor<?> constructor = (Constructor<?>) accessibleObject;
        Object[] params = new Object[constructor.getParameterCount()];
        constructor.newInstance(params);
    }
}
 
Example 8
Project: openjdk-jdk10   File: Package.java   View source code 6 votes vote down vote up
public static void checkAccess(AccessibleObject accessibleObject, Object obj)
    throws IllegalAccessException,
           InvocationTargetException,
           InstantiationException
{
    if (accessibleObject instanceof Field) {
        Field field = (Field) accessibleObject;
        field.set(obj, 42);
        field.get(obj);
    } else if (accessibleObject instanceof Method) {
        Method method = (Method) accessibleObject;
        method.invoke(obj);
    } else if (accessibleObject instanceof Constructor) {
        Constructor<?> constructor = (Constructor<?>) accessibleObject;
        Object[] params = new Object[constructor.getParameterCount()];
        constructor.newInstance(params);
    }
}
 
Example 9
Project: openjdk-jdk10   File: PublicSub.java   View source code 6 votes vote down vote up
public static void checkAccess(AccessibleObject accessibleObject, Object obj)
    throws IllegalAccessException,
           InvocationTargetException,
           InstantiationException
{
    if (accessibleObject instanceof Field) {
        Field field = (Field) accessibleObject;
        field.set(obj, 42);
        field.get(obj);
    } else if (accessibleObject instanceof Method) {
        Method method = (Method) accessibleObject;
        method.invoke(obj);
    } else if (accessibleObject instanceof Constructor) {
        Constructor<?> constructor = (Constructor<?>) accessibleObject;
        Object[] params = new Object[constructor.getParameterCount()];
        constructor.newInstance(params);
    }
}
 
Example 10
Project: monarch   File: AttributeDescriptor.java   View source code 6 votes vote down vote up
Member getReadMember(Class targetClass) throws NameNotFoundException {
  // mapping: public field (same name), method (getAttribute()),
  // method (attribute())
  List key = new ArrayList();
  key.add(targetClass);
  key.add(_name);

  Member m = (Member) _cache.get(key);
  if (m != null)
    return m;

  m = getReadField(targetClass);
  if (m == null)
    m = getReadMethod(targetClass);
  if (m != null)
    _cache.putIfAbsent(key, m);
  else
    throw new NameNotFoundException(
        LocalizedStrings.AttributeDescriptor_NO_PUBLIC_ATTRIBUTE_NAMED_0_WAS_FOUND_IN_CLASS_1
            .toLocalizedString(new Object[] {_name, targetClass.getName()}));
  // override security for nonpublic derived classes with public members
  ((AccessibleObject) m).setAccessible(true);
  return m;
}
 
Example 11
Project: Krine   File: Capabilities.java   View source code 6 votes vote down vote up
public static void setAccessibility(boolean b) {
    if (!b) {
        accessibility = false;
    } else {
        String.class.getDeclaredMethods(); // test basic access
        try {
            final AccessibleObject member = String.class.getDeclaredField("value");
            member.setAccessible(true);
            member.setAccessible(false);
        } catch (NoSuchFieldException e) {
            // ignore
        }
        accessibility = true;
    }
    KrineClassManager.clearResolveCache();
}
 
Example 12
Project: X4J   File: JavadocParanamer.java   View source code 6 votes vote down vote up
private String[] getParameterNames(AccessibleObject a, String name, Class<?>[] types, String raw) {
    if (types.length == 0)
        return new String[0];

    StringBuilder regex = new StringBuilder();
    regex.append(format(">\\Q%s\\E</A></(?:B|strong)>\\(", name));
    for (Class<?> klass : types) {
        regex.append(format(
                ",?\\s*(?:<A[^>]+>)?[\\w.]*\\Q%s\\E(?:</A>)?(?:&lt;[^&]+&gt;)?&nbsp;([^),\\s]+)",
                klass.getSimpleName()
        ));
    }
    regex.append(format("\\)</CODE>"));

    Pattern pattern = Pattern.compile(regex.toString(), Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(raw);

    if (!matcher.find())
        throw new ParameterNamesNotFoundException(a + ", " + regex);

    String[] names = new String[types.length];
    for (int i = 0 ; i < names.length ; i++)
        names[i] = matcher.group(1 + i).trim();

    return names;
}
 
Example 13
Project: openjdk-jdk10   File: Package.java   View source code 6 votes vote down vote up
public static void checkAccess(AccessibleObject accessibleObject, Object obj)
    throws IllegalAccessException,
           InvocationTargetException,
           InstantiationException
{
    if (accessibleObject instanceof Field) {
        Field field = (Field) accessibleObject;
        field.set(obj, 42);
        field.get(obj);
    } else if (accessibleObject instanceof Method) {
        Method method = (Method) accessibleObject;
        method.invoke(obj);
    } else if (accessibleObject instanceof Constructor) {
        Constructor<?> constructor = (Constructor<?>) accessibleObject;
        Object[] params = new Object[constructor.getParameterCount()];
        constructor.newInstance(params);
    }
}
 
Example 14
Project: X4J   File: JavadocParanamer.java   View source code 6 votes vote down vote up
private String[] getParameterNames(AccessibleObject a, String name, Class<?>[] types, String raw) {
    if (types.length == 0)
        return new String[0];

    StringBuilder regex = new StringBuilder();
    regex.append(format(">\\Q%s\\E</A></(?:B|strong)>\\(", name));
    for (Class<?> klass : types) {
        regex.append(format(
                ",?\\s*(?:<A[^>]+>)?[\\w.]*\\Q%s\\E(?:</A>)?(?:&lt;[^&]+&gt;)?&nbsp;([^),\\s]+)",
                klass.getSimpleName()
        ));
    }
    regex.append(format("\\)</CODE>"));

    Pattern pattern = Pattern.compile(regex.toString(), Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(raw);

    if (!matcher.find())
        throw new ParameterNamesNotFoundException(a + ", " + regex);

    String[] names = new String[types.length];
    for (int i = 0 ; i < names.length ; i++)
        names[i] = matcher.group(1 + i).trim();

    return names;
}
 
Example 15
Project: firebase-admin-java   File: CustomClassMapper.java   View source code 5 votes vote down vote up
private static String annotatedName(AccessibleObject obj) {
  if (obj.isAnnotationPresent(PropertyName.class)) {
    PropertyName annotation = obj.getAnnotation(PropertyName.class);
    return annotation.value();
  }

  return null;
}
 
Example 16
Project: X4J   File: AdaptiveParanamer.java   View source code 5 votes vote down vote up
public String[] lookupParameterNames(AccessibleObject methodOrCtor, boolean throwExceptionIfMissing) {
    for (int i = 0; i < paranamers.length; i++) {
        Paranamer paranamer = paranamers[i];
        String[] names = paranamer.lookupParameterNames(methodOrCtor, i+1 < paranamers.length ? false : throwExceptionIfMissing);
        if (names != Paranamer.EMPTY_NAMES) {
            return names;
        }
    }
    return Paranamer.EMPTY_NAMES;
}
 
Example 17
Project: springboot-spwa-gae-demo   File: MethodIntrospector.java   View source code 5 votes vote down vote up
public MethodIntrospector(AccessibleObject methodOrCtor) {
    super();
    this.methodOrCtor = methodOrCtor;
    this.classes = getClasses(methodOrCtor);
    this.types = getGenericParameterTypes(methodOrCtor);
    this.names = getParameterNames(methodOrCtor);
    this.parameterDescriptions = mergeToParameters(names, types);

}
 
Example 18
Project: aries-jpa   File: AnnotationScanner.java   View source code 5 votes vote down vote up
public List<AccessibleObject> getJpaAnnotatedMembers(Class<?> c, Class<? extends Annotation> annotation) {
    final List<AccessibleObject> jpaAnnotated = new ArrayList<AccessibleObject>();
    for (Class<?> cl = c; cl != Object.class && cl != null; cl = cl.getSuperclass()) {
        parseClass(annotation, jpaAnnotated, cl);
    }
    return jpaAnnotated;
}
 
Example 19
Project: X4J   File: CachingParanamer.java   View source code 5 votes vote down vote up
public String[] lookupParameterNames(AccessibleObject methodOrCtor, boolean throwExceptionIfMissing) {
    String[] names = methodCache.get(methodOrCtor);
    // refer PARANAMER-19
    if(names == null) {
        names = delegate.lookupParameterNames(methodOrCtor, throwExceptionIfMissing);
        methodCache.put(methodOrCtor, names);
    }
    return names;
}
 
Example 20
Project: aries-jpa   File: AnnotationScanner.java   View source code 5 votes vote down vote up
public static String getName(AccessibleObject member) {
    if (member instanceof Field) {
        return ((Field)member).getName();
    } else if (member instanceof Method) {
        Method method = (Method)member;
        String name = method.getName();
        if (!name.startsWith("set")) {
            return null;
        }
        return lowerCamelCase(name.substring(3));
    }
    throw new IllegalArgumentException();
}
 
Example 21
Project: aries-jpa   File: AnnotationScanner.java   View source code 5 votes vote down vote up
public static Class<?> getType(AccessibleObject member) {
    if (member instanceof Field) {
        return ((Field)member).getType();
    } else if (member instanceof Method) {
        return ((Method)member).getParameterTypes()[0];
    }
    throw new IllegalArgumentException();
}
 
Example 22
Project: aries-jpa   File: AnnotationScannerTest.java   View source code 5 votes vote down vote up
@Test
public void getPCAnnotatedMembersTest() {
    AnnotationScanner scanner = new AnnotationScanner();
    List<AccessibleObject> members = scanner.getJpaAnnotatedMembers(TestClass.class, PersistenceContext.class);
    Assert.assertEquals(1, members.size());
    AccessibleObject member = members.get(0);
    Assert.assertEquals(Field.class, member.getClass());
    Field field = (Field)member;
    Assert.assertEquals("em", field.getName());
}
 
Example 23
Project: aries-jpa   File: AnnotationScannerTest.java   View source code 5 votes vote down vote up
@Test
public void getPUAnnotatedMembersTest() {
    AnnotationScanner scanner = new AnnotationScanner();
    List<AccessibleObject> members = scanner.getJpaAnnotatedMembers(TestClass.class, PersistenceUnit.class);
    Assert.assertEquals(1, members.size());
    AccessibleObject member = members.get(0);
    Assert.assertEquals(Method.class, member.getClass());
    Method method = (Method)member;
    Assert.assertEquals("setEmf", method.getName());
}
 
Example 24
Project: aries-jpa   File: AnnotationScannerTest.java   View source code 5 votes vote down vote up
/**
 * When using a factory the class can be an interface. We need to make sure this does not cause a NPE
 */
@Test
public void getFactoryTest() {
    AnnotationScanner scanner = new AnnotationScanner();
    List<AccessibleObject> members = scanner.getJpaAnnotatedMembers(TestInterface.class, PersistenceUnit.class);
    Assert.assertEquals(0, members.size());
}
 
Example 25
Project: HL4A   File: VMBridge_jdk15.java   View source code 5 votes vote down vote up
@Override
protected boolean tryToMakeAccessible(AccessibleObject accessible)
{
    if (accessible.isAccessible()) {
        return true;
    }
    try {
        accessible.setAccessible(true);
    } catch (Exception ex) { }

    return accessible.isAccessible();
}
 
Example 26
Project: jaffa-framework   File: GraphMapping.java   View source code 5 votes vote down vote up
/** Returns the Field object, if available, or the setter Method, corresponding to the input dataFieldName.
 * @param dataFieldName the name of the data field.
 * @return the Field object, if available, or the setter Method, corresponding to the input dataFieldName.
 */
public AccessibleObject getDataMutator(String dataFieldName) {
    AccessibleObject accessibleObject = containsDataField(dataFieldName) ? elementMap.get(dataFieldName).getGraphField() : null;
    if (accessibleObject == null) {
        PropertyDescriptor pd = getDataFieldDescriptor(dataFieldName);
        if (pd != null) {
            accessibleObject = pd.getWriteMethod();
            if (!accessibleObject.isAccessible())
                accessibleObject.setAccessible(true);
        }
    }
    return accessibleObject;
}
 
Example 27
Project: googlecloud-techtalk   File: MethodIntrospector.java   View source code 5 votes vote down vote up
public MethodIntrospector(AccessibleObject methodOrCtor) {
    super();
    this.methodOrCtor = methodOrCtor;
    this.classes = getClasses(methodOrCtor);
    this.types = getGenericParameterTypes(methodOrCtor);
    this.names = getParameterNames(methodOrCtor);
    this.parameterDescriptions = mergeToParameters(names, types);

}
 
Example 28
Project: guava-mock   File: ForwardingWrapperTester.java   View source code 5 votes vote down vote up
/**
 * Tests that the forwarding wrapper returned by {@code wrapperFunction} properly forwards
 * method calls with parameters passed as is, return value returned as is, and exceptions
 * propagated as is.
 */
public <T> void testForwarding(
    Class<T> interfaceType, Function<? super T, ? extends T> wrapperFunction) {
  checkNotNull(wrapperFunction);
  checkArgument(interfaceType.isInterface(), "%s isn't an interface", interfaceType);
  Method[] methods = getMostConcreteMethods(interfaceType);
  AccessibleObject.setAccessible(methods, true);
  for (Method method : methods) {
    // Under java 8, interfaces can have default methods that aren't abstract.
    // No need to verify them.
    // Can't check isDefault() for JDK 7 compatibility.
    if (!Modifier.isAbstract(method.getModifiers())) {
      continue;
    }
    // The interface could be package-private or private.
    // filter out equals/hashCode/toString
    if (method.getName().equals("equals")
        && method.getParameterTypes().length == 1
        && method.getParameterTypes()[0] == Object.class) {
      continue;
    }
    if (method.getName().equals("hashCode")
        && method.getParameterTypes().length == 0) {
      continue;
    }
    if (method.getName().equals("toString")
        && method.getParameterTypes().length == 0) {
      continue;
    }
    testSuccessfulForwarding(interfaceType, method, wrapperFunction);
    testExceptionPropagation(interfaceType, method, wrapperFunction);
  }
  if (testsEquals) {
    testEquals(interfaceType, wrapperFunction);
  }
  testToString(interfaceType, wrapperFunction);
}
 
Example 29
Project: X4J   File: PositionalParanamer.java   View source code 5 votes vote down vote up
private int count(AccessibleObject methodOrCtor) {
    if (methodOrCtor instanceof Method) {
        Method method = (Method) methodOrCtor;
        return method.getParameterTypes().length;
    }
    Constructor<?> constructor = (Constructor<?>) methodOrCtor;
    return constructor.getParameterTypes().length;
}
 
Example 30
Project: lams   File: AutowiredAnnotationBeanPostProcessor.java   View source code 5 votes vote down vote up
private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) {
	for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
		AnnotationAttributes annotation = AnnotatedElementUtils.getAnnotationAttributes(ao, type.getName());
		if (annotation != null) {
			return annotation;
		}
	}
	return null;
}
 
Example 31
Project: lams   File: MemberUtils.java   View source code 5 votes vote down vote up
/**
 * XXX Default access superclass workaround
 *
 * When a public class has a default access superclass with public members,
 * these members are accessible. Calling them from compiled code works fine.
 * Unfortunately, on some JVMs, using reflection to invoke these members
 * seems to (wrongly) to prevent access even when the modifer is public.
 * Calling setAccessible(true) solves the problem but will only work from
 * sufficiently privileged code. Better workarounds would be gratefully
 * accepted.
 * @param o the AccessibleObject to set as accessible
 */
static void setAccessibleWorkaround(AccessibleObject o) {
    if (o == null || o.isAccessible()) {
        return;
    }
    Member m = (Member) o;
    if (Modifier.isPublic(m.getModifiers())
            && isPackageAccess(m.getDeclaringClass().getModifiers())) {
        try {
            o.setAccessible(true);
        } catch (SecurityException e) {
            // ignore in favor of subsequent IllegalAccessException
        }
    }
}
 
Example 32
Project: lams   File: HashCodeBuilder.java   View source code 5 votes vote down vote up
/**
 * <p>
 * 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, HashCodeBuilder builder, boolean useTransients,
        String[] excludeFields) {
    if (isRegistered(object)) {
        return;
    }
    try {
        register(object);
        Field[] fields = clazz.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            if (!ArrayUtils.contains(excludeFields, 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);
    }
}
 
Example 33
Project: lams   File: ReflectionToStringBuilder.java   View source code 5 votes vote down vote up
/**
 * <p>
 * Appends the fields and values defined by the given object of the given Class.
 * </p>
 * 
 * <p>
 * If a cycle is detected as an object is &quot;toString()'ed&quot;, such an object is rendered as if
 * <code>Object.toString()</code> had been called and not implemented by the object.
 * </p>
 * 
 * @param clazz
 *            The class of object parameter
 */
protected void appendFieldsIn(Class clazz) {
    if (clazz.isArray()) {
        this.reflectionAppendArray(this.getObject());
        return;
    }
    Field[] fields = clazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        String fieldName = field.getName();
        if (this.accept(field)) {
            try {
                // Warning: Field.get(Object) creates wrappers objects
                // for primitive types.
                Object fieldValue = this.getValue(field);
                this.append(fieldName, fieldValue);
            } catch (IllegalAccessException ex) {
                //this can't happen. Would get a Security exception
                // instead
                //throw a runtime exception in case the impossible
                // happens.
                throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage());
            }
        }
    }
}
 
Example 34
Project: lams   File: CompareToBuilder.java   View source code 5 votes vote down vote up
/**
 * <p>Appends to <code>builder</code> the comparison of <code>lhs</code>
 * to <code>rhs</code> using the fields defined in <code>clazz</code>.</p>
 * 
 * @param lhs  left-hand object
 * @param rhs  right-hand object
 * @param clazz  <code>Class</code> that defines fields to be compared
 * @param builder  <code>CompareToBuilder</code> to append to
 * @param useTransients  whether to compare transient fields
 * @param excludeFields  fields to exclude
 */
private static void reflectionAppend(
    Object lhs,
    Object rhs,
    Class clazz,
    CompareToBuilder builder,
    boolean useTransients,
    String[] excludeFields) {
    
    Field[] fields = clazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    for (int i = 0; i < fields.length && builder.comparison == 0; i++) {
        Field f = fields[i];
        if (!ArrayUtils.contains(excludeFields, f.getName())
            && (f.getName().indexOf('$') == -1)
            && (useTransients || !Modifier.isTransient(f.getModifiers()))
            && (!Modifier.isStatic(f.getModifiers()))) {
            try {
                builder.append(f.get(lhs), f.get(rhs));
            } 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");
            }
        }
    }
}
 
Example 35
Project: whackpad   File: ScriptableObject.java   View source code 5 votes vote down vote up
private static Member findAnnotatedMember(AccessibleObject[] members,
                                          Class<? extends Annotation> annotation) {
    for (AccessibleObject member : members) {
        if (member.isAnnotationPresent(annotation)) {
            return (Member) member;
        }
    }
    return null;
}
 
Example 36
Project: AppleSeed   File: MethodIntrospector.java   View source code 5 votes vote down vote up
public MethodIntrospector(AccessibleObject methodOrCtor) {
    super();
    this.methodOrCtor = methodOrCtor;
    this.classes = getClasses(methodOrCtor);
    this.types = getGenericParameterTypes(methodOrCtor);
    this.names = getParameterNames(methodOrCtor);
    this.parameterDescriptions = mergeToParameters(names, types);

}
 
Example 37
Project: nymph   File: ResovlerParamImpl.java   View source code 5 votes vote down vote up
/**
 * 根据类型将请求中的参数封装成一个对象并返回
 * @param clazz	httpBean中方法参数的类型
 * @param index	用于resultList()方法标识索引位置
 * @return
 * @throws Exception
 */
private Object resultSingle(Class<?> clazz, int index) throws Exception {
	if (cycleNumber >= 10) {
		cycleNumber++;
		return null;
	}
	
	Object instance = clazz.newInstance();
	Field[] fields = clazz.getDeclaredFields();
	AccessibleObject.setAccessible(fields, true);
	
	for (Field field : fields) {
		if (BasicUtil.isCollection(clazz)) {
			instance = resultList(field.getGenericType());
			continue;
		} 
		
		String[] vals = paramMap.get(field.getName());
		
		if (vals == null || index >= vals.length)
			continue;
		
		String param = vals[index];
		
		if (BasicUtil.isCommonType(field))
			field.set(instance, BasicUtil.convert(field, param));
		else if (field.getType() == Date.class) {
			dateFormatCheck(format);
			Date date = DateUtil.resolve(param, format);
			field.set(instance, date);
		}
		else {
			resultSingle(field.getType(), 0);
		}
	}
	return instance;
}
 
Example 38
Project: OpenJSharp   File: InstrumentationImpl.java   View source code 5 votes vote down vote up
private static void setAccessible(final AccessibleObject ao, final boolean accessible) {
    AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                ao.setAccessible(accessible);
                return null;
            }});
}
 
Example 39
Project: OpenJSharp   File: SwingLazyValue.java   View source code 5 votes vote down vote up
private void makeAccessible(final AccessibleObject object) {
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        public Void run() {
            object.setAccessible(true);
            return null;
        }
    });
}
 
Example 40
Project: OpenJSharp   File: Sdp.java   View source code 5 votes vote down vote up
private static void setAccessible(final AccessibleObject o) {
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        public Void run() {
            o.setAccessible(true);
            return null;
        }
    });
}