java.lang.reflect.Member Java Examples

The following examples show how to use java.lang.reflect.Member. 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: ObjectStreamClass.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
static MethodSignature[] removePrivateAndSort(Member[] m) {
    int numNonPrivate = 0;
    for (int i = 0; i < m.length; i++) {
        if (! Modifier.isPrivate(m[i].getModifiers())) {
            numNonPrivate++;
        }
    }
    MethodSignature[] cm = new MethodSignature[numNonPrivate];
    int cmi = 0;
    for (int i = 0; i < m.length; i++) {
        if (! Modifier.isPrivate(m[i].getModifiers())) {
            cm[cmi] = new MethodSignature(m[i]);
            cmi++;
        }
    }
    if (cmi > 0)
        Arrays.sort(cm, cm[0]);
    return cm;
}
 
Example #2
Source File: ObjectStreamClassUtil_1_3.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
static MethodSignature[] removePrivateAndSort(Member[] m) {
    int numNonPrivate = 0;
    for (int i = 0; i < m.length; i++) {
        if (! Modifier.isPrivate(m[i].getModifiers())) {
            numNonPrivate++;
        }
    }
    MethodSignature[] cm = new MethodSignature[numNonPrivate];
    int cmi = 0;
    for (int i = 0; i < m.length; i++) {
        if (! Modifier.isPrivate(m[i].getModifiers())) {
            cm[cmi] = new MethodSignature(m[i]);
            cmi++;
        }
    }
    if (cmi > 0)
        Arrays.sort(cm, cm[0]);
    return cm;
}
 
Example #3
Source File: Class.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) {
    final SecurityManager s = System.getSecurityManager();
    if (s != null) {
        /* Default policy allows access to all {@link Member#PUBLIC} members,
         * as well as access to classes that have the same class loader as the caller.
         * In all other cases, it requires RuntimePermission("accessDeclaredMembers")
         * permission.
         */
        final ClassLoader ccl = ClassLoader.getClassLoader(caller);
        final ClassLoader cl = getClassLoader0();
        if (which != Member.PUBLIC) {
            if (ccl != cl) {
                s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
            }
        }
        this.checkPackageAccess(ccl, checkProxyInterfaces);
    }
}
 
Example #4
Source File: ReflectionTypeFactory.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected <T extends Member & GenericDeclaration> void enhanceExecutable(JvmExecutable result, T member,
		String simpleName, Type[] parameterTypes, Annotation[][] annotations, int offset) {
	StringBuilder fqName = new StringBuilder(48);
	fqName.append(member.getDeclaringClass().getName());
	fqName.append('.');
	fqName.append(simpleName);
	fqName.append('(');
	InternalEList<JvmFormalParameter> parameters = (InternalEList<JvmFormalParameter>)result.getParameters();
	for (int typeIdx = offset, annotationIdx = annotations.length - parameterTypes.length + offset; typeIdx < parameterTypes.length; typeIdx++, annotationIdx++) {
		if (typeIdx != offset)
			fqName.append(',');
		Type parameterType = parameterTypes[typeIdx];
		uriHelper.computeTypeName(parameterType, fqName);
		parameters.addUnique(
				createFormalParameter(parameterType, "arg" + (typeIdx - offset), result, member,
						annotations[annotationIdx]));
	}
	fqName.append(')');
	result.internalSetIdentifier(fqName.toString());
	result.setSimpleName(simpleName);
	setVisibility(result, member.getModifiers());
}
 
Example #5
Source File: ObjectStreamClass.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
static MethodSignature[] removePrivateAndSort(Member[] m) {
    int numNonPrivate = 0;
    for (int i = 0; i < m.length; i++) {
        if (! Modifier.isPrivate(m[i].getModifiers())) {
            numNonPrivate++;
        }
    }
    MethodSignature[] cm = new MethodSignature[numNonPrivate];
    int cmi = 0;
    for (int i = 0; i < m.length; i++) {
        if (! Modifier.isPrivate(m[i].getModifiers())) {
            cm[cmi] = new MethodSignature(m[i]);
            cmi++;
        }
    }
    if (cmi > 0)
        Arrays.sort(cm, cm[0]);
    return cm;
}
 
Example #6
Source File: SimplyTimedInterceptor.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private <E extends Member & AnnotatedElement> Object timedCallable(InvocationContext invocationContext, E element)
        throws Exception {
    Set<MetricID> ids = ((MetricsRegistryImpl) registry).getMemberToMetricMappings()
            .getSimpleTimers(new CDIMemberInfoAdapter<>().convert(element));
    if (ids == null || ids.isEmpty()) {
        throw SmallRyeMetricsMessages.msg.noMetricMappedForMember(element);
    }
    List<SimpleTimer.Context> contexts = ids.stream()
            .map(metricID -> {
                SimpleTimer metric = registry.getSimpleTimers().get(metricID);
                if (metric == null) {
                    throw SmallRyeMetricsMessages.msg.noMetricFoundInRegistry(MetricType.SIMPLE_TIMER, metricID);
                }
                return metric;
            })
            .map(SimpleTimer::time)
            .collect(Collectors.toList());
    try {
        return invocationContext.proceed();
    } finally {
        for (SimpleTimer.Context timeContext : contexts) {
            timeContext.stop();
        }
    }
}
 
Example #7
Source File: Class.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) {
    final SecurityManager s = System.getSecurityManager();
    if (s != null) {
        /* Default policy allows access to all {@link Member#PUBLIC} members,
         * as well as access to classes that have the same class loader as the caller.
         * In all other cases, it requires RuntimePermission("accessDeclaredMembers")
         * permission.
         */
        final ClassLoader ccl = ClassLoader.getClassLoader(caller);
        final ClassLoader cl = getClassLoader0();
        if (which != Member.PUBLIC) {
            if (ccl != cl) {
                s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
            }
        }
        this.checkPackageAccess(ccl, checkProxyInterfaces);
    }
}
 
Example #8
Source File: ColumnMappingWizardPage.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
private ColumnDefinition[] getMappingsToAdd( )
{
	helper.clearParametersCache( );
	List<ColumnDefinition> result = new ArrayList<ColumnDefinition>( );
	
	for ( TreeItem item : classStructureTree.getTree( ).getSelection( ) )
	{
		if ( item.getData( ) instanceof TreeData
				&& ( (TreeData) item.getData( ) ).getWrappedObject( ) instanceof Member )
		{
			Member m = (Member) ( (TreeData) item.getData( ) ).getWrappedObject( );
			ColumnDefinition cm = new ColumnDefinition( getMappingPath( item ),
					Utils.getSuggestName( m ),
					Utils.getSuggestOdaType( m ) );
			result.add( cm );
		}
	}
	return result.toArray( new ColumnDefinition[0] );
}
 
Example #9
Source File: ObjectStreamClass.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
static MethodSignature[] removePrivateAndSort(Member[] m) {
    int numNonPrivate = 0;
    for (int i = 0; i < m.length; i++) {
        if (! Modifier.isPrivate(m[i].getModifiers())) {
            numNonPrivate++;
        }
    }
    MethodSignature[] cm = new MethodSignature[numNonPrivate];
    int cmi = 0;
    for (int i = 0; i < m.length; i++) {
        if (! Modifier.isPrivate(m[i].getModifiers())) {
            cm[cmi] = new MethodSignature(m[i]);
            cmi++;
        }
    }
    if (cmi > 0)
        Arrays.sort(cm, cm[0]);
    return cm;
}
 
Example #10
Source File: ExtensionBuilder.java    From mPaaS with Apache License 2.0 6 votes vote down vote up
/**
 * 从本地的Json文件加载
 */
public static ExtensionImpl newExtension(ExtensionPointImpl point,
                                         Class<?> clazz, Member member, JSONObject json)
        throws ReflectiveOperationException {
    ExtensionImpl extension = new ExtensionImpl();
    if (json != null) {
        extension.setConfig(json);
    }
    extension.setPoint(point);
    extension.setRefClass(clazz);
    extension.setElementName(member.getName());
    extension.setElementType(member instanceof Method ? ElementType.METHOD
            : ElementType.FIELD);
    // 校验、补全
    validate(extension);
    format(extension);
    return extension;
}
 
Example #11
Source File: InjectionPoint.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
private static <M extends Member & AnnotatedElement> void addInjectorsForMembers(
        TypeLiteral<?> typeLiteral, Factory<M> factory, boolean statics,
        Collection<InjectionPoint> injectionPoints, Errors errors) {
    for (M member : factory.getMembers(getRawType(typeLiteral.getType()))) {
        if (isStatic(member) != statics) {
            continue;
        }

        Inject inject = member.getAnnotation(Inject.class);
        if (inject == null) {
            continue;
        }

        try {
            injectionPoints.add(factory.create(typeLiteral, member, errors));
        } catch (ConfigurationException ignorable) {
            if (!inject.optional()) {
                errors.merge(ignorable.getErrorMessages());
            }
        }
    }
}
 
Example #12
Source File: ReflectUtil.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Does a conservative approximation of member access check. Use this if
 * you don't have an actual 'userland' caller Class/ClassLoader available.
 * This might be more restrictive than a precise member access check where
 * you have a caller, but should never allow a member access that is
 * forbidden.
 *
 * @param m the {@code Member} about to be accessed
 */
public static void conservativeCheckMemberAccess(Member m) throws SecurityException{
    final SecurityManager sm = System.getSecurityManager();
    if (sm == null)
        return;

    // Check for package access on the declaring class.
    //
    // In addition, unless the member and the declaring class are both
    // public check for access declared member permissions.
    //
    // This is done regardless of ClassLoader relations between the {@code
    // Member m} and any potential caller.

    final Class<?> declaringClass = m.getDeclaringClass();

    privateCheckPackageAccess(sm, declaringClass);

    if (Modifier.isPublic(m.getModifiers()) &&
            Modifier.isPublic(declaringClass.getModifiers()))
        return;

    // Check for declared member access.
    sm.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
}
 
Example #13
Source File: ReflectionPredicates.java    From raistlic-lib-commons-core with Apache License 2.0 6 votes vote down vote up
@Override
public boolean test(Member member) {
  return Modifier.isStatic(member.getModifiers());
}
 
Example #14
Source File: AbstractJavaLinker.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Given a reflective method or a constructor, creates a dynamic method that represents it. This method will
 * distinguish between caller sensitive and ordinary methods/constructors, and create appropriate caller sensitive
 * dynamic method when needed.
 * @param m the reflective member
 * @return the single dynamic method representing the reflective member
 */
private static SingleDynamicMethod createDynamicMethod(final AccessibleObject m) {
    if (m.isAnnotationPresent(CallerSensitive.class)) {
        // Method has @CallerSensitive annotation
        return new CallerSensitiveDynamicMethod(m);
    }
    // Method has no @CallerSensitive annotation
    final MethodHandle mh;
    try {
        mh = unreflectSafely(m);
    } catch (final IllegalAccessError e) {
        // java.lang.invoke can in some case conservatively treat as caller sensitive methods that aren't
        // marked with the annotation. In this case, we'll fall back to treating it as caller sensitive.
        return new CallerSensitiveDynamicMethod(m);
    }
    // Proceed with non-caller sensitive
    final Member member = (Member)m;
    return new SimpleDynamicMethod(mh, member.getDeclaringClass(), member.getName(), m instanceof Constructor);
}
 
Example #15
Source File: XLogUtilsTest.java    From XLog with Apache License 2.0 6 votes vote down vote up
private Member getMember(final Class clazz, final String name) {
    return new Member() {
        @Override
        public Class<?> getDeclaringClass() {
            return clazz;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public int getModifiers() {
            return 0;
        }

        @Override
        public boolean isSynthetic() {
            return false;
        }
    };
}
 
Example #16
Source File: ExtensionLoader.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static IllegalArgumentException reportError(AnnotatedElement e, String msg) {
    if (e instanceof Member) {
        return new IllegalArgumentException(msg + " at " + e + " of " + ((Member) e).getDeclaringClass());
    } else if (e instanceof Parameter) {
        return new IllegalArgumentException(msg + " at " + e + " of " + ((Parameter) e).getDeclaringExecutable() + " of "
                + ((Parameter) e).getDeclaringExecutable().getDeclaringClass());
    } else {
        return new IllegalArgumentException(msg + " at " + e);
    }
}
 
Example #17
Source File: ObjectToObjectConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private static boolean isApplicable(Member member, Class<?> sourceClass) {
	if (member instanceof Method) {
		Method method = (Method) member;
		return (!Modifier.isStatic(method.getModifiers()) ?
				ClassUtils.isAssignable(method.getDeclaringClass(), sourceClass) :
				method.getParameterTypes()[0] == sourceClass);
	}
	else if (member instanceof Constructor) {
		Constructor<?> ctor = (Constructor) member;
		return (ctor.getParameterTypes()[0] == sourceClass);
	}
	else {
		return false;
	}
}
 
Example #18
Source File: Class.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an array containing {@code Class} objects representing all
 * the public classes and interfaces that are members of the class
 * represented by this {@code Class} object.  This includes public
 * class and interface members inherited from superclasses and public class
 * and interface members declared by the class.  This method returns an
 * array of length 0 if this {@code Class} object has no public member
 * classes or interfaces.  This method also returns an array of length 0 if
 * this {@code Class} object represents a primitive type, an array
 * class, or void.
 *
 * @return the array of {@code Class} objects representing the public
 *         members of this class
 * @throws SecurityException
 *         If a security manager, <i>s</i>, is present and
 *         the caller's class loader is not the same as or an
 *         ancestor of the class loader for the current class and
 *         invocation of {@link SecurityManager#checkPackageAccess
 *         s.checkPackageAccess()} denies access to the package
 *         of this class.
 *
 * @since JDK1.1
 */
@CallerSensitive
public Class<?>[] getClasses() {
    checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);

    // Privileged so this implementation can look at DECLARED classes,
    // something the caller might not have privilege to do.  The code here
    // is allowed to look at DECLARED classes because (1) it does not hand
    // out anything other than public members and (2) public member access
    // has already been ok'd by the SecurityManager.

    return java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction<Class<?>[]>() {
            public Class<?>[] run() {
                List<Class<?>> list = new ArrayList<>();
                Class<?> currentClass = Class.this;
                while (currentClass != null) {
                    Class<?>[] members = currentClass.getDeclaredClasses();
                    for (int i = 0; i < members.length; i++) {
                        if (Modifier.isPublic(members[i].getModifiers())) {
                            list.add(members[i]);
                        }
                    }
                    currentClass = currentClass.getSuperclass();
                }
                return list.toArray(new Class<?>[0]);
            }
        });
}
 
Example #19
Source File: MemberUtils.java    From AndHook with MIT License 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 #20
Source File: ObjectStreamClassUtil_1_3.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public int compare(Object o1, Object o2) {
    String s1 = ((Member)o1).getName();
    String s2 = ((Member)o2).getName();

    if (o1 instanceof Method) {
        s1 += getSignature((Method)o1);
        s2 += getSignature((Method)o2);
    } else if (o1 instanceof Constructor) {
        s1 += getSignature((Constructor)o1);
        s2 += getSignature((Constructor)o2);
    }
    return s1.compareTo(s2);
}
 
Example #21
Source File: ObjectStreamClassUtil_1_3.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
public int compare(Object o1, Object o2) {
    String s1 = ((Member)o1).getName();
    String s2 = ((Member)o2).getName();

    if (o1 instanceof Method) {
        s1 += getSignature((Method)o1);
        s2 += getSignature((Method)o2);
    } else if (o1 instanceof Constructor) {
        s1 += getSignature((Constructor)o1);
        s2 += getSignature((Constructor)o2);
    }
    return s1.compareTo(s2);
}
 
Example #22
Source File: MethodParameter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the wrapped member.
 * @return the Method or Constructor as Member
 */
public Member getMember() {
	// NOTE: no ternary expression to retain JDK <8 compatibility even when using
	// the JDK 8 compiler (potentially selecting java.lang.reflect.Executable
	// as common type, with that new base class not available on older JDKs)
	if (this.method != null) {
		return this.method;
	}
	else {
		return this.constructor;
	}
}
 
Example #23
Source File: JPAEdmPropertyTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Override
public Member getJavaMember() {
  if (this.attributeName.equals("SOLITID")) {
    return new JPAJavaMember();
  }
  return null;
}
 
Example #24
Source File: ReflectionUtil.java    From common-utils with GNU General Public License v2.0 5 votes vote down vote up
static boolean isSynthetic(Member m) {
    if (IS_SYNTHETIC != null) {
        try {
            return ((Boolean) IS_SYNTHETIC.invoke(m, (Object[]) null)).booleanValue();
        } catch (Exception e) {
        }
    }
    return false;
}
 
Example #25
Source File: AbstractJavaLinker.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given a reflective method or a constructor, creates a dynamic method that represents it. This method will
 * distinguish between caller sensitive and ordinary methods/constructors, and create appropriate caller sensitive
 * dynamic method when needed.
 * @param m the reflective member
 * @return the single dynamic method representing the reflective member
 */
private static SingleDynamicMethod createDynamicMethod(AccessibleObject m) {
    if(CallerSensitiveDetector.isCallerSensitive(m)) {
        return new CallerSensitiveDynamicMethod(m);
    }
    final Member member = (Member)m;
    return new SimpleDynamicMethod(unreflectSafely(m), member.getDeclaringClass(), member.getName());
}
 
Example #26
Source File: LocalVariableTableParameterNameDiscoverer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
public String[] getParameterNames(Constructor<?> ctor) {
    Class<?> declaringClass = ctor.getDeclaringClass();
    Map<Member, String[]> map = this.parameterNamesCache.get(declaringClass);
    if (map == null) {
        map = inspectClass(declaringClass);
        this.parameterNamesCache.put(declaringClass, map);
    }
    if (map != NO_DEBUG_INFO_MAP) {
        return map.get(ctor);
    }
    return null;
}
 
Example #27
Source File: TypeVariableImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the <tt>GenericDeclaration</tt>  object representing the
 * generic declaration that declared this type variable.
 *
 * @return the generic declaration that declared this type variable.
 *
 * @since 1.5
 */
public D getGenericDeclaration(){
    if (genericDeclaration instanceof Class)
        ReflectUtil.checkPackageAccess((Class)genericDeclaration);
    else if ((genericDeclaration instanceof Method) ||
            (genericDeclaration instanceof Constructor))
        ReflectUtil.conservativeCheckMemberAccess((Member)genericDeclaration);
    else
        throw new AssertionError("Unexpected kind of GenericDeclaration");
    return genericDeclaration;
}
 
Example #28
Source File: Class.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
                                    int which) throws NoSuchMethodException
{
    Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
    for (Constructor<T> constructor : constructors) {
        if (arrayContentsEq(parameterTypes,
                            constructor.getParameterTypes())) {
            return getReflectionFactory().copyConstructor(constructor);
        }
    }
    throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
}
 
Example #29
Source File: ObjectStreamClass.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
public int compare(Object o1, Object o2) {
    String s1 = ((Member)o1).getName();
    String s2 = ((Member)o2).getName();

    if (o1 instanceof Method) {
        s1 += getSignature((Method)o1);
        s2 += getSignature((Method)o2);
    } else if (o1 instanceof Constructor) {
        s1 += getSignature((Constructor)o1);
        s2 += getSignature((Constructor)o2);
    }
    return s1.compareTo(s2);
}
 
Example #30
Source File: Reflections.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Get the type of the member
 *
 * @param member The member
 *
 * @return The type of the member
 *
 * @throws UnsupportedOperationException if the member is not a field, method, or constructor
 */
public static Class<?> getMemberType(Member member) {
    if (member instanceof Field) {
        return ((Field) member).getType();
    } else if (member instanceof Method) {
        return ((Method) member).getReturnType();
    } else if (member instanceof Constructor<?>) {
        return ((Constructor<?>) member).getDeclaringClass();
    } else {
        throw new UnsupportedOperationException("Cannot operate on a member of type " + member.getClass());
    }
}