Java Code Examples for java.lang.reflect.Member

The following examples show how to use java.lang.reflect.Member. 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: openjdk-jdk9   Source File: ReflectUtil.java    License: 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 2
Source Project: XLog   Source File: XLogUtilsTest.java    License: 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 3
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 4
/**
 * 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 5
Source Project: Elasticsearch   Source File: InjectionPoint.java    License: 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 6
Source Project: mPaaS   Source File: ExtensionBuilder.java    License: 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 7
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 8
Source Project: jdk8u-jdk   Source File: Class.java    License: 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 9
Source Project: birt   Source File: ColumnMappingWizardPage.java    License: 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 10
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 11
Source Project: openjdk-8-source   Source File: Class.java    License: 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 12
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 13
Source Project: jdk1.8-source-analysis   Source File: ObjectStreamClass.java    License: 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 14
Source Project: smallrye-metrics   Source File: SimplyTimedInterceptor.java    License: 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 15
Source Project: deltaspike   Source File: AnnotatedCallableImpl.java    License: Apache License 2.0 5 votes vote down vote up
private static <X, Y extends Member> List<AnnotatedParameter<X>> getAnnotatedParameters(
        AnnotatedCallableImpl<X, Y> callable, Class<?>[] parameterTypes, Type[] genericTypes,
        Map<Integer, AnnotationStore> parameterAnnotations,
        Map<Integer, Type> parameterTypeOverrides)
{
    List<AnnotatedParameter<X>> parameters = new ArrayList<AnnotatedParameter<X>>();
    int len = parameterTypes.length;

    for (int i = 0; i < len; ++i)
    {
        AnnotationBuilder builder = new AnnotationBuilder();
        if (parameterAnnotations != null && parameterAnnotations.containsKey(i))
        {
            builder.addAll(parameterAnnotations.get(i));
        }
        Type over = null;
        if (parameterTypeOverrides != null)
        {
            over = parameterTypeOverrides.get(i);
        }
        AnnotatedParameterImpl<X> p = new AnnotatedParameterImpl<X>(
                callable, parameterTypes[i], i, builder.create(), genericTypes[i], over);

        parameters.add(p);
    }
    return parameters;
}
 
Example 16
Source Project: xtext-extras   Source File: ReflectURIHelper.java    License: Eclipse Public License 2.0 5 votes vote down vote up
URI getFullURI(Member member) {
	if (member instanceof Type)
		return getFullURI((Type) member);
	StringBuilder uriBuilder = createURIBuilder();
	createResourceURI(member.getDeclaringClass(), uriBuilder);
	uriBuilder.append('#');
	createFragmentForMember(member, uriBuilder);
	return createURI(uriBuilder);
}
 
Example 17
private MethodSignature(Member m) {
    member = m;
    if (isConstructor()) {
        signature = ObjectStreamClass_1_3_1.getSignature((Constructor)m);
    } else {
        signature = ObjectStreamClass_1_3_1.getSignature((Method)m);
    }
}
 
Example 18
@Override
MethodHandle getTarget(final MethodHandles.Lookup lookup) {
    if(target instanceof Method) {
        final MethodHandle mh = Lookup.unreflect(lookup, (Method)target);
        if(Modifier.isStatic(((Member)target).getModifiers())) {
            return StaticClassIntrospector.editStaticMethodHandle(mh);
        }
        return mh;
    }
    return StaticClassIntrospector.editConstructorMethodHandle(Lookup.unreflectConstructor(lookup,
            (Constructor<?>)target));
}
 
Example 19
@Override
public void checkMemberAccess(Class<?> clazz, int which) {
    if (which == Member.DECLARED && isRelevant() &&
            "com.android.ide.common.rendering.RenderSecurityManager".equals(clazz.getName())) {
        throw RenderSecurityException.create("Reflection", clazz.getName());
    }
}
 
Example 20
Source Project: AndHook   Source File: XposedHelpers.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the index of the first parameter declared with the given type.
 *
 * @throws NoSuchFieldError if there is no parameter with that type.
 */
public static int getFirstParameterIndexByType(final Member method, final Class<?> type) {
    final Class<?>[] classes = (method instanceof Method) ?
            ((Method) method).getParameterTypes() : ((Constructor<?>) method).getParameterTypes();
    for (int i = 0; i < classes.length; ++i) {
        if (classes[i] == type) {
            return i;
        }
    }
    throw new NoSuchFieldError("No parameter of type " + type + " found in " + method);
}
 
Example 21
@Override
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 22
@Override
@Nullable
public String[] getParameterNames(Method method) {
	Method originalMethod = BridgeMethodResolver.findBridgedMethod(method);
	Class<?> declaringClass = originalMethod.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(originalMethod);
	}
	return null;
}
 
Example 23
Source Project: JsDroidCmd   Source File: VMBridge_jdk15.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
public boolean isVarArgs(Member member) {
    if (member instanceof Method)
        return ((Method) member).isVarArgs();
    else if (member instanceof Constructor)
        return ((Constructor<?>) member).isVarArgs();
    else
        return false;
}
 
Example 24
/***
 * TODO,还需要加上Parameter
 * @param member
 * @param annoType
 * @return
 */
public static <A extends Annotation> A getAnntationUntilParent(Member member ,Class<A > annoType){
    A anno =null;
    
    if (Method.class.isInstance(member)){
        Method method =((Method)member);
        anno=method .getAnnotation(annoType);
    } 
    
    if (anno==null){
        return member.getDeclaringClass().getAnnotation(annoType);
    }
    
    return null;
}
 
Example 25
Source Project: vraptor4   Source File: ReflectionProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
private Predicate<Member> notFromObject() {
	return new Predicate<Member>() {
		@Override
		public boolean apply(Member input) {
			return !input.getDeclaringClass().equals(Object.class);
		}
	};
}
 
Example 26
Source Project: spring-analysis-note   Source File: ReflectivePropertyAccessor.java    License: MIT License 5 votes vote down vote up
/**
 * Get the last read invoker pair.
 * @deprecated as of 4.3.15 since it is not used within the framework anymore
 */
@Deprecated
@Nullable
public Member getLastReadInvokerPair() {
	InvokerPair lastReadInvoker = this.lastReadInvokerPair;
	return (lastReadInvoker != null ? lastReadInvoker.member : null);
}
 
Example 27
Source Project: spring-analysis-note   Source File: InjectionMetadata.java    License: MIT License 5 votes vote down vote up
public void checkConfigMembers(RootBeanDefinition beanDefinition) {
	Set<InjectedElement> checkedElements = new LinkedHashSet<>(this.injectedElements.size());
	for (InjectedElement element : this.injectedElements) {
		Member member = element.getMember();
		if (!beanDefinition.isExternallyManagedConfigMember(member)) {
			beanDefinition.registerExternallyManagedConfigMember(member);
			checkedElements.add(element);
			if (logger.isTraceEnabled()) {
				logger.trace("Registered injected element on class [" + this.targetClass.getName() + "]: " + element);
			}
		}
	}
	this.checkedElements = checkedElements;
}
 
Example 28
Source Project: spring-analysis-note   Source File: RootBeanDefinition.java    License: MIT License 5 votes vote down vote up
public void registerExternallyManagedConfigMember(Member configMember) {
	synchronized (this.postProcessingLock) {
		if (this.externallyManagedConfigMembers == null) {
			this.externallyManagedConfigMembers = new HashSet<>(1);
		}
		this.externallyManagedConfigMembers.add(configMember);
	}
}
 
Example 29
Source Project: jdk8u_jdk   Source File: Class.java    License: 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 30
Source Project: hottub   Source File: TypeVariableImpl.java    License: 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;
}