java.lang.reflect.Member源码实例Demo

类java.lang.reflect.Member源码实例Demo

下面列出了java.lang.reflect.Member 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: openjdk-jdk9   文件: ReflectUtil.java
/**
 * 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);
}
 
源代码2 项目: XLog   文件: XLogUtilsTest.java
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;
        }
    };
}
 
源代码3 项目: openjdk-jdk9   文件: ObjectStreamClass.java
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;
}
 
源代码4 项目: openjdk-jdk9   文件: AbstractJavaLinker.java
/**
 * 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);
}
 
源代码5 项目: Elasticsearch   文件: InjectionPoint.java
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());
            }
        }
    }
}
 
源代码6 项目: mPaaS   文件: ExtensionBuilder.java
/**
 * 从本地的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;
}
 
源代码7 项目: TencentKona-8   文件: ObjectStreamClass.java
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;
}
 
源代码8 项目: jdk8u-jdk   文件: Class.java
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);
    }
}
 
源代码9 项目: birt   文件: ColumnMappingWizardPage.java
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] );
}
 
源代码10 项目: openjdk-8   文件: ObjectStreamClassUtil_1_3.java
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;
}
 
源代码11 项目: openjdk-8-source   文件: Class.java
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);
    }
}
 
源代码12 项目: xtext-extras   文件: ReflectionTypeFactory.java
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());
}
 
源代码13 项目: jdk1.8-source-analysis   文件: ObjectStreamClass.java
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;
}
 
源代码14 项目: smallrye-metrics   文件: SimplyTimedInterceptor.java
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();
        }
    }
}
 
源代码15 项目: deltaspike   文件: AnnotatedCallableImpl.java
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;
}
 
源代码16 项目: xtext-extras   文件: ReflectURIHelper.java
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);
}
 
源代码17 项目: hottub   文件: ObjectStreamClass_1_3_1.java
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);
    }
}
 
@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));
}
 
源代码19 项目: javaide   文件: RenderSecurityManager.java
@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());
    }
}
 
源代码20 项目: AndHook   文件: XposedHelpers.java
/**
 * 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);
}
 
@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;
}
 
@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;
}
 
源代码23 项目: JsDroidCmd   文件: VMBridge_jdk15.java
@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;
}
 
源代码24 项目: stategen   文件: ReflectionUtil.java
/***
 * 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;
}
 
源代码25 项目: vraptor4   文件: ReflectionProviderTest.java
private Predicate<Member> notFromObject() {
	return new Predicate<Member>() {
		@Override
		public boolean apply(Member input) {
			return !input.getDeclaringClass().equals(Object.class);
		}
	};
}
 
/**
 * 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);
}
 
源代码27 项目: spring-analysis-note   文件: InjectionMetadata.java
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;
}
 
源代码28 项目: spring-analysis-note   文件: RootBeanDefinition.java
public void registerExternallyManagedConfigMember(Member configMember) {
	synchronized (this.postProcessingLock) {
		if (this.externallyManagedConfigMembers == null) {
			this.externallyManagedConfigMembers = new HashSet<>(1);
		}
		this.externallyManagedConfigMembers.add(configMember);
	}
}
 
源代码29 项目: jdk8u_jdk   文件: Class.java
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));
}
 
源代码30 项目: hottub   文件: TypeVariableImpl.java
/**
 * 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;
}