java.lang.reflect.AccessibleObject Java Examples

The following examples show how to use java.lang.reflect.AccessibleObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NotQueryableException.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that the provided accessor method has not been marked with a Queryable(false).
 *
 * @param accessor accessor method
 *
 * @throws NotQueryableException - If accessor method has been marked as not queryable
 */
public static void throwIfNotQueryable( final AccessibleObject accessor )
{
    Queryable queryable = accessor.getAnnotation( Queryable.class );
    if( queryable != null && !queryable.value() )
    {
        throw new NotQueryableException(
            String.format(
                "%1$s \"%2$s\" (%3$s) is not queryable as has been marked with @Queryable(false)",
                Classes.RAW_CLASS.apply( GenericPropertyInfo.propertyTypeOf( accessor ) ).getSimpleName(),
                ( (Member) accessor ).getName(),
                ( (Member) accessor ).getDeclaringClass().getName()
            )
        );
    }
}
 
Example #2
Source File: CapsuleTestUtils.java    From capsule with Eclipse Public License 1.0 6 votes vote down vote up
public static <T extends AccessibleObject> T accessible(T x) {
    if (!x.isAccessible())
        x.setAccessible(true);

    if (x instanceof Field) {
        Field field = (Field) x;
        if ((field.getModifiers() & Modifier.FINAL) != 0) {
            try {
                Field modifiersField = Field.class.getDeclaredField("modifiers");
                modifiersField.setAccessible(true);
                modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
            } catch (ReflectiveOperationException e) {
                throw new AssertionError(e);
            }
        }
    }

    return x;
}
 
Example #3
Source File: ReflectUtil.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 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 #4
Source File: AssociationsModel.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public AssociationModel getAssociation( AccessibleObject accessor )
    throws IllegalArgumentException
{
    AssociationModel associationModel = mapAccessorAssociationModel.get( accessor );
    if( associationModel == null )
    {
        throw new IllegalArgumentException( "No association found with name:" + ( (Member) accessor ).getName() );
    }
    return associationModel;
}
 
Example #5
Source File: InstrumentationImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 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 #6
Source File: ExpressionLanguageOGNLImpl.java    From oval with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Boolean setup(final Map context, final Object target, final Member member, final String propertyName) {
   final AccessibleObject accessible = (AccessibleObject) member;
   final Boolean oldAccessibleState = accessible.isAccessible();

   if (!oldAccessibleState) {
      ReflectionUtils.setAccessible(accessible, true);
   }
   return oldAccessibleState;
}
 
Example #7
Source File: BaseMockTest.java    From jparsec with Apache License 2.0 5 votes vote down vote up
private static List<Field> getMockFields(Class<?> type) {
  List<Field> fields = new ArrayList<Field>();
  for (Field field : type.getDeclaredFields()) {
    if (field.isAnnotationPresent(Mock.class)) {
      fields.add(field);
    }
  }
  AccessibleObject.setAccessible(fields.toArray(new Field[fields.size()]), true);
  Class<?> superclass = type.getSuperclass();
  if (superclass != null) {
    fields.addAll(getMockFields(superclass));
  }
  fields = Collections.unmodifiableList(fields);
  return fields;
}
 
Example #8
Source File: AccessibleObjectTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.lang.reflect.AccessibleObject#isAccessible()
 */
public void test_isAccessible() {
    // Test for method boolean
    // java.lang.reflect.AccessibleObject.isAccessible()
    try {
        AccessibleObject ao = TestClass.class.getField("aField");
        ao.setAccessible(true);
        assertTrue("Returned false to isAccessible", ao.isAccessible());
        ao.setAccessible(false);
        assertTrue("Returned true to isAccessible", !ao.isAccessible());
    } catch (Exception e) {
        fail("Exception during test : " + e.getMessage());
    }
}
 
Example #9
Source File: CallerSensitiveDetector.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
boolean isCallerSensitive(final AccessibleObject o) {
    for(final Annotation a: o.getAnnotations()) {
        if(String.valueOf(a).equals(CALLER_SENSITIVE_ANNOTATION_STRING)) {
            return true;
        }
    }
    return false;
}
 
Example #10
Source File: ClassTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testCertainClassLiterals() {
  assertEquals("java.lang.Object", Object.class.getName());
  assertEquals("java.lang.String", String.class.getName());
  assertEquals("java.lang.Cloneable", Cloneable.class.getName());
  assertEquals("java.lang.Number", Number.class.getName());
  assertEquals("java.lang.Iterable", Iterable.class.getName());
  assertEquals("java.lang.Throwable", Throwable.class.getName());
  assertEquals("java.lang.reflect.AccessibleObject", AccessibleObject.class.getName());
  assertEquals("java.lang.reflect.Constructor", Constructor.class.getName());
  assertEquals("java.lang.reflect.Field", Field.class.getName());
  assertEquals("java.lang.reflect.Method", Method.class.getName());
}
 
Example #11
Source File: ReflectionUtil.java    From uima-uimafit with Apache License 2.0 5 votes vote down vote up
/**
 * Equivalent to {@link AccessibleObject#isAnnotationPresent(Class)} but handles uimaFIT legacy
 * annotations.
 * 
 * @param aObject
 *          the object to analyze
 * @param aAnnotationClass
 *          the annotation to check for
 * @return whether the annotation is present
 */
public static boolean isAnnotationPresent(AccessibleObject aObject,
        Class<? extends Annotation> aAnnotationClass) {
  // First check if the desired annotation is present
  // UIMA-3853 workaround for IBM Java 8 beta 3
  if (aObject.getAnnotation(aAnnotationClass) != null) {
    return true;
  }
  
  // If not present, check if an equivalent legacy annotation is present
  return LegacySupport.getInstance().isAnnotationPresent(aObject, aAnnotationClass);
}
 
Example #12
Source File: ScriptableObject.java    From openbd-core with GNU General Public License v3.0 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 #13
Source File: DeclarationsTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testSetImplementedInterfaces() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("class BaseClass {}");
  _builder.newLine();
  _builder.append("interface Interface {}");
  _builder.newLine();
  final Procedure1<CompilationUnitImpl> _function = (CompilationUnitImpl it) -> {
    final MutableClassDeclaration baseClass = it.getTypeLookup().findClass("BaseClass");
    final MutableInterfaceDeclaration interf = it.getTypeLookup().findInterface("Interface");
    final TypeReference objectType = baseClass.getExtendedClass();
    Assert.assertEquals("Object", objectType.getSimpleName());
    Assert.assertTrue(IterableExtensions.isEmpty(baseClass.getImplementedInterfaces()));
    final TypeReference superType = it.getTypeReferenceProvider().newTypeReference(AccessibleObject.class);
    baseClass.setExtendedClass(superType);
    Assert.assertEquals("AccessibleObject", baseClass.getExtendedClass().getSimpleName());
    Assert.assertTrue(IterableExtensions.isEmpty(baseClass.getImplementedInterfaces()));
    baseClass.setExtendedClass(null);
    Assert.assertEquals("Object", baseClass.getExtendedClass().getSimpleName());
    Assert.assertTrue(IterableExtensions.isEmpty(baseClass.getImplementedInterfaces()));
    TypeReference _newTypeReference = it.getTypeReferenceProvider().newTypeReference(interf);
    baseClass.setImplementedInterfaces(Collections.<TypeReference>unmodifiableList(CollectionLiterals.<TypeReference>newArrayList(_newTypeReference)));
    Assert.assertEquals("Interface", IterableExtensions.head(baseClass.getImplementedInterfaces()).getSimpleName());
    baseClass.setImplementedInterfaces(Collections.<TypeReference>unmodifiableList(CollectionLiterals.<TypeReference>newArrayList()));
    Assert.assertTrue(IterableExtensions.isEmpty(baseClass.getImplementedInterfaces()));
  };
  this.asCompilationUnit(this.validFile(_builder), _function);
}
 
Example #14
Source File: ModelUtils.java    From elepy with Apache License 2.0 5 votes vote down vote up
/**
 * Gets all fields that are not marked as hidden and all methods annotated with @Generated
 */
public static List<AccessibleObject> getAccessibleObjects(Class<?> cls) {
    return Stream.concat(
            ReflectionUtils.getAllFields(cls).stream()
                    .filter(field -> !field.isAnnotationPresent(Hidden.class)),
            Stream.of(cls.getDeclaredMethods())
                    .filter(method -> method.isAnnotationPresent(Generated.class))
    ).collect(Collectors.toList());
}
 
Example #15
Source File: AccessibleObjectTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_getAnnotations() throws Exception {
    AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod");
    Annotation[] annotations = ao.getAnnotations();
    assertEquals(2, annotations.length);

    Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
    ignoreOrder.add(annotations[0].annotationType());
    ignoreOrder.add(annotations[1].annotationType());

    assertTrue("Missing @AnnotationRuntime0",
            ignoreOrder.contains(AnnotationRuntime0.class));
    assertTrue("Missing @AnnotationRuntime1",
            ignoreOrder.contains(AnnotationRuntime1.class));
}
 
Example #16
Source File: MemberUtils.java    From kcanotify_h5-master with GNU General Public License v3.0 5 votes vote down vote up
/**
 * XXX Default access superclass workaround
 * <p>
 * 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) prevent access even when the modifier 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) { // NOPMD
            // ignore in favor of subsequent IllegalAccessException
        }
    }
}
 
Example #17
Source File: CompositeParameterNameExtractor.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
@Override
public String[] extractNames(AccessibleObject ctorOrMethod) {
    for (ParameterNameExtractor extractor : extractors) {
        String[] names = extractor.extractNames(ctorOrMethod);
        if (names != null) return names;
    }
    return null;
}
 
Example #18
Source File: CustomClassMapper.java    From firebase-android-sdk with Apache License 2.0 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 #19
Source File: Reflections.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
/**
 * Set the accessibility flag on the {@link AccessibleObject} as described in
 * {@link AccessibleObject#setAccessible(boolean)} within the context of a {@link PrivilegedAction}.
 *
 * @param <A>
 *            member the accessible object type
 * @param member
 *            the accessible object
 * @return the accessible object after the accessible flag has been altered
 */
public static <A extends AccessibleObject> A setAccessible(final A member)
{
    AccessController.doPrivileged(new PrivilegedAction<Void>()
    {
        @Override
        public Void run()
        {
            member.setAccessible(true);
            return null;
        }
    });
    return member;
}
 
Example #20
Source File: ClassTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testCertainSuperclasses() {
  assertNull("Non-null Object superclass", Object.class.getSuperclass());
  assertNull("Non-null Cloneable superclass", Cloneable.class.getSuperclass());
  assertNull("Non-null Iterable superclass", Iterable.class.getSuperclass());

  assertEquals("Bad String superclass", Object.class, String.class.getSuperclass());
  assertEquals("Bad Number superclass", Object.class, Number.class.getSuperclass());
  assertEquals("Bad Throwable superclass", Object.class, Throwable.class.getSuperclass());
  assertEquals("Bad AccessibleObject superclass", Object.class,
      AccessibleObject.class.getSuperclass());

  // Check a String subclass.
  assertEquals("Bad String superclass", Object.class, "foo".getClass().getSuperclass());
}
 
Example #21
Source File: ReflectionUtil.java    From common-utils with GNU General Public License v2.0 5 votes vote down vote up
public static void forceAccess(AccessibleObject object) {
    if (object == null || object.isAccessible()) {
        return;
    }
    try {
        object.setAccessible(true);
    } catch (SecurityException e) {
        throw ExceptionUtil.toRuntimeException(e);
    }
}
 
Example #22
Source File: ReflectUtil.java    From PoseidonX with Apache License 2.0 5 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 #23
Source File: AssociationModel.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public AssociationModel( AccessibleObject accessor,
                         ValueConstraintsInstance valueConstraintsInstance,
                         ValueConstraintsInstance associationConstraintsInstance,
                         MetaInfo metaInfo
)
{
    super( accessor, valueConstraintsInstance, associationConstraintsInstance, metaInfo );
}
 
Example #24
Source File: CallerSensitiveDetector.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Override
boolean isCallerSensitive(final AccessibleObject o) {
    for(final Annotation a: o.getAnnotations()) {
        if(String.valueOf(a).equals(CALLER_SENSITIVE_ANNOTATION_STRING)) {
            return true;
        }
    }
    return false;
}
 
Example #25
Source File: MetaInfoDeclaration.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public MetaInfo metaInfoFor( AccessibleObject accessor )
{
    final MethodInfo methodInfo = matches( accessor );
    if( methodInfo == null )
    {
        return null;
    }
    return methodInfo.metaInfo;
}
 
Example #26
Source File: ChangeEnumValues.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private static void blankField(Class<?> enumClass, String fieldName) throws NoSuchFieldException,
        IllegalAccessException {
    for (Field field : Class.class.getDeclaredFields()) {
        if (field.getName().contains(fieldName)) {
            AccessibleObject.setAccessible(new Field[]{field}, true);
            setFailSafeFieldValue(field, enumClass, null);
            break;
        }
    }
}
 
Example #27
Source File: InstrumentationImpl.java    From jdk8u_jdk with GNU General Public License v2.0 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 #28
Source File: ValueStateInstance.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings( "unchecked" )
public <T> PropertyInstance<T> propertyFor( AccessibleObject accessor )
    throws IllegalArgumentException
{
    PropertyInstance<T> property = (PropertyInstance<T>) properties.get( accessor );

    if( property == null )
    {
        throw new IllegalArgumentException( "No such property:" + accessor );
    }

    return property;
}
 
Example #29
Source File: OWLSchemaPersistingManager.java    From anno4j with Apache License 2.0 5 votes vote down vote up
/**
 * Persists the information that a property is the inverse of another property to the default graph of the connected triplestore.
 * All properties with {@link InverseOf} annotation are considered.
 * @param annotatedObjects The {@link Iri} annotated objects that should be considered.
 * @throws RepositoryException Thrown on error regarding the connected triplestore.
 * @throws UpdateExecutionException Thrown if an error occurred while executing the update.
 */
private void persistInverseOf(Collection<AccessibleObject> annotatedObjects) throws RepositoryException, UpdateExecutionException {
    // Get those methods and fields that have the @InverseOf annotation:
    Collection<AccessibleObject> inverseOfObjects = filterObjectsWithAnnotation(annotatedObjects, InverseOf.class);

    for (AccessibleObject object : inverseOfObjects) {
        String iri = getIriFromObject(object);

        InverseOf inverseOfAnnotation = object.getAnnotation(InverseOf.class);

        StringBuilder query = new StringBuilder(QUERY_PREFIX)
                .append(" INSERT DATA { ");
        for (String inversePropertyIri : inverseOfAnnotation.value()) {
            query.append("<").append(iri).append("> owl:inverseOf ")
                    .append("<").append(inversePropertyIri).append("> . ")
                 .append("<").append(inversePropertyIri).append("> owl:inverseOf ")
                 .append("<").append(iri).append("> . ");
        }
        query.append("}");

        // Prepare the update query and execute it:
        try {
            Update update = getConnection().prepareUpdate(query.toString());
            update.execute();
        } catch (MalformedQueryException e) {
            throw new UpdateExecutionException();
        }
    }
}
 
Example #30
Source File: AccessibleObjectTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_getDeclaredAnnotations() throws Exception {
    AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod");
    Annotation[] annotations = ao.getDeclaredAnnotations();
    assertEquals(2, annotations.length);

    Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
    ignoreOrder.add(annotations[0].annotationType());
    ignoreOrder.add(annotations[1].annotationType());

    assertTrue("Missing @AnnotationRuntime0",
            ignoreOrder.contains(AnnotationRuntime0.class));
    assertTrue("Missing @AnnotationRuntime1",
            ignoreOrder.contains(AnnotationRuntime1.class));
}