Java Code Examples for java.lang.reflect.AccessibleObject

The following examples show how to use java.lang.reflect.AccessibleObject. These examples are extracted from open source projects. 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 Project: attic-polygene-java   Source File: NotQueryableException.java    License: 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
/**
 * 放回一个可以访问的字段或者方法
 *
 */
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 3
Source Project: capsule   Source File: CapsuleTestUtils.java    License: 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 4
Source Project: jkes   Source File: EventSupport.java    License: Apache License 2.0 5 votes vote down vote up
private CascadeType[] getCascadeTypes(AccessibleObject accessibleObject) {
    CascadeType[] cascadeTypes = null;
    if(accessibleObject.isAnnotationPresent(OneToMany.class)) {
        cascadeTypes = accessibleObject.getAnnotation(OneToMany.class).cascade();
    }else if(accessibleObject.isAnnotationPresent(ManyToOne.class)) {
        cascadeTypes = accessibleObject.getAnnotation(ManyToOne.class).cascade();
    }else if(accessibleObject.isAnnotationPresent(ManyToMany.class)) {
        cascadeTypes = accessibleObject.getAnnotation(ManyToMany.class).cascade();
    }
    return cascadeTypes;
}
 
Example 5
Source Project: j2objc   Source File: AccessibleObjectTest.java    License: 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));
}
 
Example 6
Source Project: manifold   Source File: ReflectUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testOverrideOffsetForJava12() throws NoSuchFieldException
{
  // since we run this test in Java 8, we can test that the approximated offset for Java 12 matches the actual offset
  long approximateOffset = AccessibleObject_layout.getOverrideOffset( NecessaryEvilUtil.getUnsafe() );
  long actualOffset = NecessaryEvilUtil.getUnsafe().objectFieldOffset( AccessibleObject.class.getDeclaredField( "override" ) );
  assertEquals( actualOffset, approximateOffset );
}
 
Example 7
Source Project: jdk8u_jdk   Source File: SwingLazyValue.java    License: GNU General Public License v2.0 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 8
Source Project: attic-polygene-java   Source File: Annotations.java    License: Apache License 2.0 5 votes vote down vote up
public static List<Annotation> findAccessorAndTypeAnnotationsIn(AccessibleObject accessor) {
    Stream<Annotation> stream = Stream.concat(
            Arrays.stream(accessor.getAnnotations()),
            interfacesOf(typeOf(accessor)).flatMap(ANNOTATIONS_OF)
    );
    Collector<Annotation, ?, List<Annotation>> collector = Collectors.toList();
    return stream.collect(collector);
}
 
Example 9
Source Project: qaf   Source File: MetaDataScanner.java    License: MIT License 5 votes vote down vote up
/**
 * Scans all annotation except @Test, and generates map.
 * 
 * @param MethodOrFileld
 * @return
 * @throws Exception
 */
public static Map<String, Object> getMetadata(AccessibleObject methodOrFileld, boolean excludeTest) {
	Map<String, Object> metadata = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
	metadata.putAll(metadataFromClass(methodOrFileld));

	try {
		Annotation[] allAnnotations = methodOrFileld.getAnnotations();
		for (Annotation annotation : allAnnotations) {
			if (excludeTest && annotation instanceof Test)
				continue;

			Method[] annotationMethods = annotation.annotationType().getDeclaredMethods();
			for (Method annotationMethod : annotationMethods) {
				Object objVal = annotationMethod.invoke(annotation);
				if (annotation instanceof MetaData) {
					@SuppressWarnings("unchecked")
					Map<String, Object> map = new Gson().fromJson((String) objVal, Map.class);
					metadata.putAll(map);
				} else {
					metadata.put(annotationMethod.getName(), objVal);
				}
			}
		}
	} catch (Exception e) {
		logger.error(e);
	}
	return metadata;
}
 
Example 10
Source Project: web-data-extractor   Source File: AnnotationDataReader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reads {@link AnnotationData annotation data} on provided accessible object.
 * If annotation is not presented, <code>null</code> is returned.
 */
public D readAnnotationData(AccessibleObject accessibleObject) {
    A annotation = accessibleObject.getAnnotation(annotationClass);
    if (annotation == null) {
        return null;
    }

    return createAnnotationData(annotation);
}
 
Example 11
Source Project: gama   Source File: AbstractGamlAdditions.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void _unary(final String[] keywords, final AccessibleObject method, final Class[] classes,
		final int[] expectedContentTypes, final Object returnClassOrType, final boolean c, final int t,
		final int content, final int index, final int contentContentType, final GamaGetter.Unary helper) {
	final Signature signature = new Signature(classes);
	final String plugin = GamaBundleLoader.CURRENT_PLUGIN_NAME;
	for (final String keyword : keywords) {
		final String kw = keyword;
		if (!OPERATORS.containsKey(kw)) {
			OPERATORS.put(kw, GamaMapFactory.createUnordered());
		}
		final Map<Signature, OperatorProto> map = OPERATORS.get(kw);
		if (!map.containsKey(signature)) {
			OperatorProto proto;
			IType rt;
			if (returnClassOrType instanceof Class) {
				rt = Types.get((Class) returnClassOrType);
			} else {
				rt = (IType) returnClassOrType;
			}
			proto = new OperatorProto(kw, method, helper, c, false, rt, signature,
					IExpression.class.equals(classes[0]), t, content, index, contentContentType,
					expectedContentTypes, plugin);
			map.put(signature, proto);
		}
	}

}
 
Example 12
Source Project: smallrye-config   Source File: SecuritySupport.java    License: Apache License 2.0 5 votes vote down vote up
static void setAccessible(AccessibleObject object, boolean flag) {
    if (System.getSecurityManager() == null) {
        object.setAccessible(flag);
    } else {
        AccessController.doPrivileged((PrivilegedAction<Void>) () -> {

            try {
                object.setAccessible(flag);
            } catch (SecurityException ex) {
                ConfigLogging.log.failedToSetAccessible(ex, object.toString());
            }
            return null;
        });
    }
}
 
Example 13
Source Project: openjdk-jdk8u-backup   Source File: Sdp.java    License: GNU General Public License v2.0 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;
        }
    });
}
 
Example 14
Source Project: attic-polygene-java   Source File: ValueStateInstance.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings( "unchecked" )
public <T> AssociationInstance<T> associationFor( AccessibleObject accessor )
{
    AssociationInstance<T> association = (AssociationInstance<T>) associations.get( accessor );

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

    return association;
}
 
Example 15
Source Project: android_9.0.0_r45   Source File: ViewDebug.java    License: Apache License 2.0 5 votes vote down vote up
private static Field[] getExportedPropertyFields(Class<?> klass) {
    if (sFieldsForClasses == null) {
        sFieldsForClasses = new HashMap<Class<?>, Field[]>();
    }
    if (sAnnotations == null) {
        sAnnotations = new HashMap<AccessibleObject, ExportedProperty>(512);
    }

    final HashMap<Class<?>, Field[]> map = sFieldsForClasses;

    Field[] fields = map.get(klass);
    if (fields != null) {
        return fields;
    }

    try {
        final Field[] declaredFields = klass.getDeclaredFieldsUnchecked(false);
        final ArrayList<Field> foundFields = new ArrayList<Field>();
        for (final Field field : declaredFields) {
          // Fields which can't be resolved have a null type.
          if (field.getType() != null && field.isAnnotationPresent(ExportedProperty.class)) {
              field.setAccessible(true);
              foundFields.add(field);
              sAnnotations.put(field, field.getAnnotation(ExportedProperty.class));
          }
        }
        fields = foundFields.toArray(new Field[foundFields.size()]);
        map.put(klass, fields);
    } catch (NoClassDefFoundError e) {
        throw new AssertionError(e);
    }

    return fields;
}
 
Example 16
Source Project: astor   Source File: CompareToBuilder.java    License: GNU General Public License v2.0 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();
    List excludedFieldList = excludeFields != null ? Arrays.asList(excludeFields) : Collections.EMPTY_LIST;
    AccessibleObject.setAccessible(fields, true);
    for (int i = 0; i < fields.length && builder.comparison == 0; i++) {
        Field f = fields[i];
        if (!excludedFieldList.contains(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 17
@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 Project: anno4j   Source File: OWLSchemaPersistingManager.java    License: 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 19
Source Project: attic-polygene-java   Source File: ValueStateInstance.java    License: 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 20
private static void setAccessible(final AccessibleObject ao, final boolean accessible) {
    AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                ao.setAccessible(accessible);
                return null;
            }});
}
 
Example 21
Source Project: carbon-device-mgt   Source File: ChangeEnumValues.java    License: 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 22
Source Project: attic-polygene-java   Source File: MetaInfoDeclaration.java    License: 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 23
@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 24
Source Project: attic-polygene-java   Source File: AssociationModel.java    License: 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 25
Source Project: PoseidonX   Source File: ReflectUtil.java    License: 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 26
Source Project: common-utils   Source File: ReflectionUtil.java    License: 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 27
Source Project: j2objc   Source File: ClassTest.java    License: 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 28
Source Project: deltaspike   Source File: Reflections.java    License: 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 29
Source Project: j2objc   Source File: AccessibleObjectTest.java    License: 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 30
Source Project: openbd-core   Source File: ScriptableObject.java    License: 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;
}