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 Project: openjdk-jdk9   Author: AdoptOpenJDK   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   Author: promeG   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
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: ObjectStreamClass.java    License: 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 #4
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: AbstractJavaLinker.java    License: 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 #5
Source Project: raistlic-lib-commons-core   Author: raistlic   File: ReflectionPredicates.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean test(Member member) {
  return Modifier.isStatic(member.getModifiers());
}
 
Example #6
Source Project: Elasticsearch   Author: baidu   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 #7
Source Project: mPaaS   Author: lihangqi   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 #8
Source Project: TencentKona-8   Author: Tencent   File: ObjectStreamClass.java    License: 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 #9
Source Project: jdk8u-jdk   Author: frohoff   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 #10
Source Project: birt   Author: eclipse   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 #11
Source Project: openjdk-8   Author: bpupadhyaya   File: ObjectStreamClassUtil_1_3.java    License: 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 #12
Source Project: openjdk-8-source   Author: keerath   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 #13
Source Project: xtext-extras   Author: eclipse   File: ReflectionTypeFactory.java    License: 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 #14
Source Project: jdk1.8-source-analysis   Author: raysonfang   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 #15
Source Project: smallrye-metrics   Author: smallrye   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 #16
Source Project: deltaspike   Author: apache   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 #17
Source Project: xtext-extras   Author: eclipse   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 #18
Source Project: hottub   Author: dsrg-uoft   File: ObjectStreamClass_1_3_1.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 #19
Source Project: jdk8u_nashorn   Author: JetBrains   File: CallerSensitiveDynamicMethod.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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 #20
Source Project: javaide   Author: tranleduy2000   File: RenderSecurityManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
@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 #21
Source Project: AndHook   Author: asLody   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 #22
Source Project: dolphin   Author: beihaifeiwu   File: LocalVariableTableParameterNameDiscoverer.java    License: Apache License 2.0 5 votes vote down vote up
@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 #23
Source Project: spring-analysis-note   Author: Vip-Augus   File: LocalVariableTableParameterNameDiscoverer.java    License: MIT License 5 votes vote down vote up
@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 #24
Source Project: JsDroidCmd   Author: coolwho   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 #25
Source Project: stategen   Author: stategen   File: ReflectionUtil.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/***
 * 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 #26
Source Project: vraptor4   Author: caelum   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 #27
Source Project: spring-analysis-note   Author: Vip-Augus   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 #28
Source Project: spring-analysis-note   Author: Vip-Augus   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 #29
Source Project: spring-analysis-note   Author: Vip-Augus   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 #30
Source Project: jdk8u_jdk   Author: JetBrains   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));
}