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

下面列出了怎么用java.lang.reflect.Modifier的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: openjdk-jdk8u   文件: 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();

    checkPackageAccess(declaringClass);

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

    // Check for declared member access.
    sm.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
}
 
源代码2 项目: JDKSourceCode1.8   文件: JMX.java
/**
 * <p>Test whether an interface is an MXBean interface.
 * An interface is an MXBean interface if it is public,
 * annotated {@link MXBean &#64;MXBean} or {@code @MXBean(true)}
 * or if it does not have an {@code @MXBean} annotation
 * and its name ends with "{@code MXBean}".</p>
 *
 * @param interfaceClass The candidate interface.
 *
 * @return true if {@code interfaceClass} is a
 * {@link javax.management.MXBean compliant MXBean interface}
 *
 * @throws NullPointerException if {@code interfaceClass} is null.
 */
public static boolean isMXBeanInterface(Class<?> interfaceClass) {
    if (!interfaceClass.isInterface())
        return false;
    if (!Modifier.isPublic(interfaceClass.getModifiers()) &&
        !Introspector.ALLOW_NONPUBLIC_MBEAN) {
        return false;
    }
    MXBean a = interfaceClass.getAnnotation(MXBean.class);
    if (a != null)
        return a.value();
    return interfaceClass.getName().endsWith("MXBean");
    // We don't bother excluding the case where the name is
    // exactly the string "MXBean" since that would mean there
    // was no package name, which is pretty unlikely in practice.
}
 
源代码3 项目: anyline   文件: BeanUtil.java
public static boolean setFieldValue(Object obj, Field field, Object value){ 
	if(null == obj || null == field){ 
		return false; 
	} 
	if(Modifier.isStatic(field.getModifiers())){ 
		return false; 
	} 
	try{
		if(field.isAccessible()){
			//可访问属性
			field.set(obj, value);
		}else{
			//不可访问属性
			field.setAccessible(true);
			field.set(obj, value);
			field.setAccessible(false);
		}
	}catch(Exception e){
		e.printStackTrace();
		return false;
	}
	return true; 
}
 
源代码4 项目: javageci   文件: Selector.java
/**
 * -
 * <p>
 * ### Class and method checking selectors
 *
 * <p> These conditions work on classes and on methods. Applying
 * them on a field will throw exception.
 */
private void methodAndClassOnlySelectors() {
    /**
     * -
     *
     * * `abstract` is `true` if the type of method is abstract.
     *
     */
    selector("abstract", m -> only(m, Class.class, Method.class) && Modifier.isAbstract(getModifiers(m)));
    /**
     * -
     *
     * * `implements` is `true` if the class implements at least one
     * interface. When applied to a method it is `true` if the
     * method implements a method of the same name and argument
     * types in one of the interfaces the class directly or
     * indirectly implements. In other words it means that there is
     * an interface that declares this method and this method is an
     * implementation (not abstract).
     *
     */
    selector("implements", m -> only(m, Class.class, Method.class) && methodOrClassImplements(m));
}
 
源代码5 项目: jdk8u60   文件: JMX.java
/**
 * <p>Test whether an interface is an MXBean interface.
 * An interface is an MXBean interface if it is public,
 * annotated {@link MXBean &#64;MXBean} or {@code @MXBean(true)}
 * or if it does not have an {@code @MXBean} annotation
 * and its name ends with "{@code MXBean}".</p>
 *
 * @param interfaceClass The candidate interface.
 *
 * @return true if {@code interfaceClass} is a
 * {@link javax.management.MXBean compliant MXBean interface}
 *
 * @throws NullPointerException if {@code interfaceClass} is null.
 */
public static boolean isMXBeanInterface(Class<?> interfaceClass) {
    if (!interfaceClass.isInterface())
        return false;
    if (!Modifier.isPublic(interfaceClass.getModifiers()) &&
        !Introspector.ALLOW_NONPUBLIC_MBEAN) {
        return false;
    }
    MXBean a = interfaceClass.getAnnotation(MXBean.class);
    if (a != null)
        return a.value();
    return interfaceClass.getName().endsWith("MXBean");
    // We don't bother excluding the case where the name is
    // exactly the string "MXBean" since that would mean there
    // was no package name, which is pretty unlikely in practice.
}
 
源代码6 项目: javageci   文件: GeciReflectionTools.java
/**
 * Convert an int containing modifiers bits to string containing the Java names of the modifiers space separated.
 *
 * @param modifiers to be converted to string
 * @return the space separated modifiers or empty string in case there is no modifier bit set in {@code modifiers}
 */
public static String unmask(int modifiers) {
    final StringBuilder s = new StringBuilder();
    final BiConsumer<Predicate<Integer>, String> check = (Predicate<Integer> predicate, String text) -> {
        if (predicate.test(modifiers)) {
            s.append(text);
        }
    };
    check.accept(Modifier::isPrivate, "private ");
    check.accept(Modifier::isProtected, "protected ");
    check.accept(Modifier::isPublic, "public ");
    check.accept(Modifier::isFinal, "final ");
    check.accept(Modifier::isStatic, "static ");
    check.accept(Modifier::isSynchronized, "synchronized ");
    check.accept(Modifier::isVolatile, "volatile ");
    check.accept(Modifier::isStrict, "strictfp ");
    check.accept(Modifier::isAbstract, "abstract ");
    check.accept(Modifier::isTransient, "transient ");
    return s.toString().trim();
}
 
源代码7 项目: poi-excel-utils   文件: ExcelUtils.java
private static void readConfigParamVerify(ExcelReadSheetProcessor<?> sheetProcessor,
                                          Map<Integer, Map<String, ExcelReadFieldMappingAttribute>> fieldMapping) {
    Class<?> clazz = sheetProcessor.getTargetClass();

    for (Entry<Integer, Map<String, ExcelReadFieldMappingAttribute>> indexFieldMapping : fieldMapping.entrySet()) {
        for (Map.Entry<String, ExcelReadFieldMappingAttribute> filedMapping : indexFieldMapping.getValue().entrySet()) {
            String fieldName = filedMapping.getKey();
            if (fieldName != null) {
                PropertyDescriptor pd = getPropertyDescriptor(clazz, fieldName);
                if (pd == null || pd.getWriteMethod() == null) {
                    throw new IllegalArgumentException("In fieldMapping config {colIndex:"
                                                       + indexFieldMapping.getKey() + "["
                                                       + convertColIntIndexToCharIndex(indexFieldMapping.getKey())
                                                       + "]<->fieldName:" + filedMapping.getKey() + "}, "
                                                       + " class " + clazz.getName() + " can't find field '"
                                                       + filedMapping.getKey() + "' and can not also find "
                                                       + filedMapping.getKey() + "'s writter method.");
                }
                if (!Modifier.isPublic(pd.getWriteMethod().getDeclaringClass().getModifiers())) {
                    pd.getWriteMethod().setAccessible(true);
                }
            }
        }
    }
}
 
static boolean isStaticallyNameable(Class<?> cls) {
    if (cls == Object.class)
        return true;
    while (cls.isArray())
        cls = cls.getComponentType();
    if (cls.isPrimitive())
        return true;  // int[].class, for example
    if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
        return false;
    // could use VerifyAccess.isClassAccessible but the following is a safe approximation
    if (cls.getClassLoader() != Object.class.getClassLoader())
        return false;
    if (VerifyAccess.isSamePackage(MethodHandle.class, cls))
        return true;
    if (!Modifier.isPublic(cls.getModifiers()))
        return false;
    for (Class<?> pkgcls : STATICALLY_INVOCABLE_PACKAGES) {
        if (VerifyAccess.isSamePackage(pkgcls, cls))
            return true;
    }
    return false;
}
 
源代码9 项目: intellij-quarkus   文件: ExternalSystemTestCase.java
private void resetClassFields(final Class<?> aClass) {
  if (aClass == null) return;

  final Field[] fields = aClass.getDeclaredFields();
  for (Field field : fields) {
    final int modifiers = field.getModifiers();
    if ((modifiers & Modifier.FINAL) == 0
        && (modifiers & Modifier.STATIC) == 0
        && !field.getType().isPrimitive()) {
      field.setAccessible(true);
      try {
        field.set(this, null);
      }
      catch (IllegalAccessException e) {
        e.printStackTrace();
      }
    }
  }

  if (aClass == ExternalSystemTestCase.class) return;
  resetClassFields(aClass.getSuperclass());
}
 
源代码10 项目: kogito-runtimes   文件: MVELConstraintBuilder.java
@Override
public boolean areEqualityCompatible(Class<?> c1, Class<?> c2) {
    if (c1 == NullType.class || c2 == NullType.class) {
        return true;
    }
    if (c1 == String.class || c2 == String.class) {
        return true;
    }
    Class<?> boxed1 = convertFromPrimitiveType(c1);
    Class<?> boxed2 = convertFromPrimitiveType(c2);
    if (boxed1.isAssignableFrom(boxed2) || boxed2.isAssignableFrom(boxed1)) {
        return true;
    }
    if (Number.class.isAssignableFrom(boxed1) && Number.class.isAssignableFrom(boxed2)) {
        return true;
    }
    return !Modifier.isFinal(c1.getModifiers()) && !Modifier.isFinal(c2.getModifiers());
}
 
源代码11 项目: mogu_blog_v2   文件: JsonUtils.java
/**
 * JSON 转 ArrayList
 *
 * @author [email protected]
 * @date 2018年10月27日下午4:43:25
 */
public static ArrayList<?> jsonArrayToArrayList(String jsonArray, Class<?> clazz) {

    Gson gson = new GsonBuilder()
            .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .serializeNulls()
            .create();
    ArrayList<?> list = null;
    try {

        list = (ArrayList<?>) gson.fromJson(jsonArray, clazz);
    } catch (JsonSyntaxException e) {
        e.printStackTrace();
    }
    return list;
}
 
源代码12 项目: glowroot   文件: AnalyzedMethod.java
boolean isOverriddenBy(String methodName, List<Type> parameterTypes) {
    if (Modifier.isStatic(modifiers())) {
        return false;
    }
    if (Modifier.isPrivate(modifiers())) {
        return false;
    }
    if (!methodName.equals(name())) {
        return false;
    }
    if (parameterTypes.size() != parameterTypes().size()) {
        return false;
    }
    for (int i = 0; i < parameterTypes.size(); i++) {
        if (!parameterTypes.get(i).getClassName().equals(parameterTypes().get(i))) {
            return false;
        }
    }
    return true;
}
 
@Test
public void allKnownMappingTypesTest() throws NoSuchFieldException {
	for (Method method : Struct.class.getMethods()) {
		String methodName = method.getName();
		// ignoring private methods, ones not named like a getter. Getters must also
		// only take the column index or name
		if (!Modifier.isPublic(method.getModifiers()) || !methodName.startsWith("get")
				|| method.getParameterCount() != 1
				|| DISREGARDED_METHOD_NAMES.contains(methodName)) {
			continue;
		}
		Class returnType = ConversionUtils.boxIfNeeded(method.getReturnType());
		if (ConversionUtils.isIterableNonByteArrayType(returnType)) {
			Class innerReturnType = (Class) ((ParameterizedType) method
					.getGenericReturnType()).getActualTypeArguments()[0];
			assertThat(StructAccessor.readIterableMapping.keySet()).contains(innerReturnType);
		}
		else {
			assertThat(StructAccessor.singleItemReadMethodMapping.keySet()).contains(returnType);
		}
	}
}
 
源代码14 项目: Tangram-Android   文件: ExposureSupport.java
private void findExposureMethods(Method[] methods) {
    for (Method method : methods) {
        String methodName = method.getName();
        if (isValidExposureMethodName(methodName)) {
            int modifiers = method.getModifiers();
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                Class<?>[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length == 3) {
                    Class<?> viewType = parameterTypes[0];
                    Class<?> cellType = parameterTypes[1];
                    Class<?> clickIntType = parameterTypes[2];
                    if (View.class.isAssignableFrom(viewType)
                            && BaseCell.class.isAssignableFrom(cellType)
                            && (clickIntType.equals(int.class) || clickIntType
                            .equals(Integer.class))) {
                        mOnExposureMethods.put(viewType, new OnTraceMethod(3, method));
                    }
                }
            }
        }
    }
}
 
源代码15 项目: Cubes   文件: LuaMapping.java
public static LuaTable mapping(Class<?> c) {
  try {
    LuaTable luaTable = new LuaTable();
    for (Field field : c.getFields()) {
      if (!Modifier.isStatic(field.getModifiers())) continue;
      if (LuaValue.class.isAssignableFrom(field.getType())) {
        luaTable.set(field.getName(), (LuaValue) field.get(null));
      }
      if (field.getType().equals(Class.class)) {
        luaTable.set(field.getName(), mapping((Class<?>) field.get(null)));
      }
    }
    return new ReadOnlyLuaTable(luaTable);
  } catch (Exception e) {
    throw new CubesException("Failed to create lua api", e);
  }
}
 
源代码16 项目: calcite   文件: ScalarFunctionImpl.java
/**
 * Creates {@link org.apache.calcite.schema.ScalarFunction} for each method in
 * a given class.
 */
public static ImmutableMultimap<String, ScalarFunction> createAll(
    Class<?> clazz) {
  final ImmutableMultimap.Builder<String, ScalarFunction> builder =
      ImmutableMultimap.builder();
  for (Method method : clazz.getMethods()) {
    if (method.getDeclaringClass() == Object.class) {
      continue;
    }
    if (!Modifier.isStatic(method.getModifiers())
        && !classHasPublicZeroArgsConstructor(clazz)) {
      continue;
    }
    final ScalarFunction function = create(method);
    builder.put(method.getName(), function);
  }
  return builder.build();
}
 
源代码17 项目: jdk8u60   文件: SwingTest.java
private void start() throws Throwable {
    do {
        if ((this.method != null) && Modifier.isStatic(this.method.getModifiers())) {
            run(); // invoke static method on the current thread
        }
        else {
            SwingUtilities.invokeLater(this); // invoke on the event dispatch thread
        }
        Toolkit tk = Toolkit.getDefaultToolkit();
        if (tk instanceof SunToolkit) {
            SunToolkit stk = (SunToolkit) tk;
            stk.realSync(); // wait until done
        }
    }
    while (this.frame != null);
    if (this.error != null) {
        throw this.error;
    }
}
 
源代码18 项目: clj-graal-docs   文件: Reflector2.java
public static boolean isAccessibleMatch(Method lhs, Method rhs, Object target) {
        if(!lhs.getName().equals(rhs.getName())
                        || !Modifier.isPublic(lhs.getDeclaringClass().getModifiers())
                        || !canAccess(lhs, target))
        {
                return false;
        }

        Class[] types1 = lhs.getParameterTypes();
        Class[] types2 = rhs.getParameterTypes();
        if(types1.length != types2.length)
                return false;

        boolean match = true;
        for (int i=0; i<types1.length; ++i)
        {
                if(!types1[i].isAssignableFrom(types2[i]))
                {
                        match = false;
                        break;
                }
        }
        return match;
}
 
/**
 * Returns a value indicating whether the operator can transform the given method.
 */
@Override
public boolean canMutate(Method method) {
    try {
        Class<?> returnClass = getAppropriateReturnClass(method);

        if(returnClass.equals(String.class)
                || !belongsToJavaPackages(returnClass)
                || Modifier.isAbstract(returnClass.getModifiers())) {
            return false;
        }
        for (Constructor<?> publicConstructor : returnClass.getConstructors()) {
            if (publicConstructor.getParameters().length == 0) {
                return true;
            }
        }
        return false;
    }
    catch (ClassNotFoundException e) {
        return false;
    }
}
 
源代码20 项目: jdk1.8-source-analysis   文件: ObjectStreamClass.java
/**
 * Returns subclass-accessible no-arg constructor of first non-serializable
 * superclass, or null if none found.  Access checks are disabled on the
 * returned constructor (if any).
 */
private static Constructor<?> getSerializableConstructor(Class<?> cl) {
    Class<?> initCl = cl;
    while (Serializable.class.isAssignableFrom(initCl)) {
        if ((initCl = initCl.getSuperclass()) == null) {
            return null;
        }
    }
    try {
        Constructor<?> cons = initCl.getDeclaredConstructor((Class<?>[]) null);
        int mods = cons.getModifiers();
        if ((mods & Modifier.PRIVATE) != 0 ||
            ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
             !packageEquals(cl, initCl)))
        {
            return null;
        }
        cons = reflFactory.newConstructorForSerialization(cl, cons);
        cons.setAccessible(true);
        return cons;
    } catch (NoSuchMethodException ex) {
        return null;
    }
}
 
源代码21 项目: astor   文件: TestReadableDurationConverter.java
public void testSingleton() throws Exception {
    Class cls = ReadableDurationConverter.class;
    assertEquals(false, Modifier.isPublic(cls.getModifiers()));
    assertEquals(false, Modifier.isProtected(cls.getModifiers()));
    assertEquals(false, Modifier.isPrivate(cls.getModifiers()));
    
    Constructor con = cls.getDeclaredConstructor((Class[]) null);
    assertEquals(1, cls.getDeclaredConstructors().length);
    assertEquals(true, Modifier.isProtected(con.getModifiers()));
    
    Field fld = cls.getDeclaredField("INSTANCE");
    assertEquals(false, Modifier.isPublic(fld.getModifiers()));
    assertEquals(false, Modifier.isProtected(fld.getModifiers()));
    assertEquals(false, Modifier.isPrivate(fld.getModifiers()));
}
 
源代码22 项目: xtext-lib   文件: ToStringBuilder.java
@GwtIncompatible("java.lang.reflect.Field")
private ToStringBuilder addField(final Field field) {
	if (!Modifier.isStatic(field.getModifiers())) {
		field.setAccessible(true);
		try {
			add(field.getName(), field.get(instance));
		} catch(IllegalAccessException e) {
			throw Exceptions.sneakyThrow(e);
		}
	}
	return this;
}
 
源代码23 项目: groovy   文件: MixinInMetaClass.java
private static CachedConstructor findDefaultConstructor(CachedClass mixinClass) {
    for (CachedConstructor constr : mixinClass.getConstructors()) {
        if (!Modifier.isPublic(constr.getModifiers()))
            continue;

        CachedClass[] classes = constr.getParameterTypes();
        if (classes.length == 0)
            return constr;
    }

    throw new GroovyRuntimeException("No default constructor for class " + mixinClass.getName() + "! Can't be mixed in.");
}
 
源代码24 项目: openjdk-jdk8u   文件: ObjectReader.java
public void doByte(ByteField field, boolean isVMField) {
   java.lang.reflect.Field f = null;
   try {
      f = readField(field);
      if (Modifier.isFinal(f.getModifiers())) return;
      f.setAccessible(true);
      f.setByte(obj, field.getValue(getObj()));
   } catch (Exception ex) {
      printFieldSetError(f, ex);
   }
}
 
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest linkRequest, final LinkerServices linkerServices) throws Exception {
    final LinkRequest request = linkRequest.withoutRuntimeContext(); // Nashorn has no runtime context
    final Object self = request.getReceiver();
    if (self.getClass() != StaticClass.class) {
        return null;
    }
    final Class<?> receiverClass = ((StaticClass) self).getRepresentedClass();

    Bootstrap.checkReflectionAccess(receiverClass, true);
    final CallSiteDescriptor desc = request.getCallSiteDescriptor();
    // We intercept "new" on StaticClass instances to provide additional capabilities
    if ("new".equals(desc.getNameToken(CallSiteDescriptor.OPERATOR))) {
        if (! Modifier.isPublic(receiverClass.getModifiers())) {
            throw ECMAErrors.typeError("new.on.nonpublic.javatype", receiverClass.getName());
        }

        // make sure new is on accessible Class
        Context.checkPackageAccess(receiverClass);

        // Is the class abstract? (This includes interfaces.)
        if (NashornLinker.isAbstractClass(receiverClass)) {
            // Change this link request into a link request on the adapter class.
            final Object[] args = request.getArguments();
            args[0] = JavaAdapterFactory.getAdapterClassFor(new Class<?>[] { receiverClass }, null,
                    linkRequest.getCallSiteDescriptor().getLookup());
            final LinkRequest adapterRequest = request.replaceArguments(request.getCallSiteDescriptor(), args);
            final GuardedInvocation gi = checkNullConstructor(delegate(linkerServices, adapterRequest), receiverClass);
            // Finally, modify the guard to test for the original abstract class.
            return gi.replaceMethods(gi.getInvocation(), Guards.getIdentityGuard(self));
        }
        // If the class was not abstract, just delegate linking to the standard StaticClass linker. Make an
        // additional check to ensure we have a constructor. We could just fall through to the next "return"
        // statement, except we also insert a call to checkNullConstructor() which throws an ECMAScript TypeError
        // with a more intuitive message when no suitable constructor is found.
        return checkNullConstructor(delegate(linkerServices, request), receiverClass);
    }
    // In case this was not a "new" operation, just delegate to the the standard StaticClass linker.
    return delegate(linkerServices, request);
}
 
源代码26 项目: jdk8u60   文件: ObjectReader.java
public void doChar(CharField field, boolean isVMField) {
   java.lang.reflect.Field f = null;
   try {
      f = readField(field);
      if (Modifier.isFinal(f.getModifiers())) return;
      f.setAccessible(true);
      f.setChar(obj, field.getValue(getObj()));
   } catch (Exception ex) {
      printFieldSetError(f, ex);
   }
}
 
源代码27 项目: jdk1.8-source-analysis   文件: ObjectStreamClass.java
/**
 * Returns non-static, non-abstract method with given signature provided it
 * is defined by or accessible (via inheritance) by the given class, or
 * null if no match found.  Access checks are disabled on the returned
 * method (if any).
 */
private static Method getInheritableMethod(Class<?> cl, String name,
                                           Class<?>[] argTypes,
                                           Class<?> returnType)
{
    Method meth = null;
    Class<?> defCl = cl;
    while (defCl != null) {
        try {
            meth = defCl.getDeclaredMethod(name, argTypes);
            break;
        } catch (NoSuchMethodException ex) {
            defCl = defCl.getSuperclass();
        }
    }

    if ((meth == null) || (meth.getReturnType() != returnType)) {
        return null;
    }
    meth.setAccessible(true);
    int mods = meth.getModifiers();
    if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) {
        return null;
    } else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) {
        return meth;
    } else if ((mods & Modifier.PRIVATE) != 0) {
        return (cl == defCl) ? meth : null;
    } else {
        return packageEquals(cl, defCl) ? meth : null;
    }
}
 
源代码28 项目: es6draft   文件: Code.java
public MethodCode newConstructor(int access, MethodTypeDescriptor methodDescriptor, String signature,
        String[] exceptions) {
    if ((access & ~Modifier.constructorModifiers()) != 0) {
        throw new IllegalArgumentException();
    }
    methodCount += 1;
    return new MethodCode(this, access, "<init>", methodDescriptor,
            classWriter.visitMethod(access, "<init>", methodDescriptor.descriptor(), signature, exceptions));
}
 
源代码29 项目: coming   文件: NPEfix_0089_s.java
/**
 * <p>Returns the desired Method much like <code>Class.getMethod</code>, however
 * it ensures that the returned Method is from a public class or interface and not
 * from an anonymous inner class. This means that the Method is invokable and
 * doesn't fall foul of Java bug
 * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957">4071957</a>).
 *
 *  <code><pre>Set set = Collections.unmodifiableSet(...);
 *  Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty",  new Class[0]);
 *  Object result = method.invoke(set, new Object[]);</pre></code>
 * </p>
 *
 * @param cls  the class to check, not null
 * @param methodName  the name of the method
 * @param parameterTypes  the list of parameters
 * @return the method
 * @throws NullPointerException if the class is null
 * @throws SecurityException if a a security violation occured
 * @throws NoSuchMethodException if the method is not found in the given class
 *  or if the metothod doen't conform with the requirements
 */
public static Method getPublicMethod(Class<?> cls, String methodName, Class<?> parameterTypes[])
        throws SecurityException, NoSuchMethodException {

    Method declaredMethod = cls.getMethod(methodName, parameterTypes);
    if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) {
        return declaredMethod;
    }

    List<Class<?>> candidateClasses = new ArrayList<Class<?>>();
    candidateClasses.addAll(getAllInterfaces(cls));
    candidateClasses.addAll(getAllSuperclasses(cls));

    for (Class<?> candidateClass : candidateClasses) {
        if (!Modifier.isPublic(candidateClass.getModifiers())) {
            continue;
        }
        Method candidateMethod;
        try {
            candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
        } catch (NoSuchMethodException ex) {
            continue;
        }
        if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) {
            return candidateMethod;
        }
    }

    throw new NoSuchMethodException("Can't find a public method for " +
            methodName + " " + org.apache.commons.lang3.ArrayUtils.toString(parameterTypes));
}
 
源代码30 项目: HotswapAgent   文件: ClassSignatureBase.java
private boolean makeAccessible(Method method) {
    if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
            && !method.isAccessible()) {
        method.setAccessible(true);
        return true;
    }
    return false;
}