下面列出了java.lang.reflect.Modifier#isPublic ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* <p>Return an accessible method (that is, one that can be invoked via
* reflection) that implements the specified Method. If no such method
* can be found, return <code>null</code>.</p>
*
* @param method The method that we wish to call
* @return The accessible method
*/
public static Method getAccessibleMethod(Method method) {
if (!MemberUtils.isAccessible(method)) {
return null;
}
// If the declaring class is public, we are done
Class cls = method.getDeclaringClass();
if (Modifier.isPublic(cls.getModifiers())) {
return method;
}
String methodName = method.getName();
Class[] parameterTypes = method.getParameterTypes();
// Check the implemented interfaces and subinterfaces
method = getAccessibleMethodFromInterfaceNest(cls, methodName,
parameterTypes);
// Check the superclass chain
if (method == null) {
method = getAccessibleMethodFromSuperclass(cls, methodName,
parameterTypes);
}
return method;
}
protected JSJavaScriptEngine(boolean debug) {
this.debug = debug;
ScriptEngineManager manager = new ScriptEngineManager();
engine = manager.getEngineByName("javascript");
if (engine == null) {
throw new RuntimeException("can't load JavaScript engine");
}
Method[] methods = getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
Method m = methods[i];
if (! Modifier.isPublic(m.getModifiers())) {
continue;
}
Class[] argTypes = m.getParameterTypes();
if (argTypes.length == 1 &&
argTypes[0] == Object[].class) {
putFunction(this, m);
}
}
}
protected static void appendAttributes(Map<Object, Object> parameters, Object config, String prefix) {
if (config == null) {
return;
}
Method[] methods = config.getClass().getMethods();
for (Method method : methods) {
try {
String name = method.getName();
if ((name.startsWith("get") || name.startsWith("is"))
&& !"getClass".equals(name)
&& Modifier.isPublic(method.getModifiers())
&& method.getParameterTypes().length == 0
&& isPrimitive(method.getReturnType())) {
Parameter parameter = method.getAnnotation(Parameter.class);
if (parameter == null || !parameter.attribute())
continue;
String key;
if (parameter.key().length() > 0) {
key = parameter.key();
} else {
int i = name.startsWith("get") ? 3 : 2;
key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1);
}
Object value = method.invoke(config);
if (value != null) {
if (prefix != null && prefix.length() > 0) {
key = prefix + "." + key;
}
parameters.put(key, value);
}
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
private Method getPublicMethodRecursive(String name, Class<?>[] parameterTypes) {
// search superclasses
for (Class<?> c = this; c != null; c = c.getSuperclass()) {
Method result = c.getDeclaredMethodInternal(name, parameterTypes);
if (result != null && Modifier.isPublic(result.getAccessFlags())) {
return result;
}
}
return findInterfaceMethod(name, parameterTypes);
}
@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);
}
private static Map<String, Object> createValueMapForAnnotation(Class<?> clz) {
Map<String, Object> map = new HashMap<>();
for (Method method : clz.getDeclaredMethods()) {
int modifiers = method.getModifiers();
if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
map.put(method.getName(), "value");
}
}
return map;
}
/**
* <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));
}
void setAccessModifier(int modifier) {
if (Modifier.isPublic(modifier))
accessModifier = AccessStates.PUBLIC;
else if (Modifier.isProtected(modifier))
accessModifier = AccessStates.PROTECTED;
else if (Modifier.isPrivate(modifier))
accessModifier = AccessStates.PRIVATE;
else
accessModifier = AccessStates.DEFAULT;
}
/**
* Returns a direct MethodHandle for the {@code writeReplace} method on
* a serializable class.
* The single argument of {@link MethodHandle#invoke} is the serializable
* object.
*
* @param cl the Serializable class
* @return a direct MethodHandle for the {@code writeReplace} method of the class or
* {@code null} if the class does not have a {@code writeReplace} method
*/
private MethodHandle getReplaceResolveForSerialization(Class<?> cl,
String methodName) {
if (!Serializable.class.isAssignableFrom(cl)) {
return null;
}
Class<?> defCl = cl;
while (defCl != null) {
try {
Method m = defCl.getDeclaredMethod(methodName);
if (m.getReturnType() != Object.class) {
return null;
}
int mods = m.getModifiers();
if (Modifier.isStatic(mods) | Modifier.isAbstract(mods)) {
return null;
} else if (Modifier.isPublic(mods) | Modifier.isProtected(mods)) {
// fall through
} else if (Modifier.isPrivate(mods) && (cl != defCl)) {
return null;
} else if (!packageEquals(cl, defCl)) {
return null;
}
try {
// Normal return
m.setAccessible(true);
return MethodHandles.lookup().unreflect(m);
} catch (IllegalAccessException ex0) {
// setAccessible should prevent IAE
throw new InternalError("Error", ex0);
}
} catch (NoSuchMethodException ex) {
defCl = defCl.getSuperclass();
}
}
return null;
}
/**
* <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));
}
/**
* 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
*/
public static void makeAccessible(Field field) {
if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier
.isFinal(field.getModifiers())) && !field.isAccessible()) {
field.setAccessible(true);
}
}
/**
* <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 + " " + ArrayUtils.toString(parameterTypes));
}
/**
* <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));
}
protected boolean isEligible(Method javaMethod) {
return Modifier.isPublic(javaMethod.getModifiers())
&& !Modifier.isStatic(javaMethod.getModifiers())
&& !javaMethod.isBridge()
&& !javaMethod.getDeclaringClass().equals(Object.class);
}
private static boolean isResourceKeyField(Field field) {
int modifiers = field.getModifiers();
return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers);
}
/**
* for external java functions only: reports on whether or not
* the specified method is found in the specifed class.
*/
private boolean hasMethods() {
LiteralExpr arg = (LiteralExpr)_arg;
// Get the class name from the namespace uri
String className = getClassNameFromUri(_namespaceOfFunct);
// Get the method name from the argument to function-available
String methodName = null;
int colonIndex = _nameOfFunct.indexOf(":");
if (colonIndex > 0) {
String functionName = _nameOfFunct.substring(colonIndex+1);
int lastDotIndex = functionName.lastIndexOf('.');
if (lastDotIndex > 0) {
methodName = functionName.substring(lastDotIndex+1);
if (className != null && !className.equals(""))
className = className + "." + functionName.substring(0, lastDotIndex);
else
className = functionName.substring(0, lastDotIndex);
}
else
methodName = functionName;
}
else
methodName = _nameOfFunct;
if (className == null || methodName == null) {
return false;
}
// Replace the '-' characters in the method name
if (methodName.indexOf('-') > 0)
methodName = replaceDash(methodName);
try {
final Class clazz = ObjectFactory.findProviderClass(className, true);
if (clazz == null) {
return false;
}
final Method[] methods = clazz.getMethods();
for (int i = 0; i < methods.length; i++) {
final int mods = methods[i].getModifiers();
if (Modifier.isPublic(mods) && Modifier.isStatic(mods)
&& methods[i].getName().equals(methodName))
{
return true;
}
}
}
catch (ClassNotFoundException e) {
return false;
}
return false;
}
private Field[] getAllFields(Class<T> type) {
List<Field> allFields = new ArrayList<>();
Class<?> nextClass = type;
while (nextClass != Object.class) {
Field[] declaredFields = nextClass.getDeclaredFields();
if (declaredFields != null) {
for (Field f : declaredFields) {
int modifiers = f.getModifiers();
if (Modifier.isStatic(modifiers)) {
continue;
}
if (Modifier.isFinal(modifiers)) {
continue;
}
if (Modifier.isTransient(modifiers)) {
continue;
}
if (!Modifier.isPublic(modifiers)) {
// 如果不是public的,就必须有 get、set 方法
if (getGetMethod(methods, f) == null) {
continue;
}
if (getSetMethod(methods, f) == null) {
continue;
}
}
allFields.add(f);
}
}
nextClass = nextClass.getSuperclass();
}
return UnsafeUtil.sortFieldsByOffset(allFields);
}
/**
* Gathers methods that can be implemented or overridden from the specified type into this factory's
* {@link #methodInfos} set. It will add all non-final, non-static methods that are either public or protected from
* the type if the type itself is public. If the type is a class, the method will recursively invoke itself for its
* superclass and the interfaces it implements, and add further methods that were not directly declared on the
* class.
* @param type the type defining the methods.
*/
private void gatherMethods(final Class<?> type) throws AdaptationException {
if (Modifier.isPublic(type.getModifiers())) {
final Method[] typeMethods = type.isInterface() ? type.getMethods() : type.getDeclaredMethods();
for (final Method typeMethod: typeMethods) {
final String name = typeMethod.getName();
if(name.startsWith(SUPER_PREFIX)) {
continue;
}
final int m = typeMethod.getModifiers();
if (Modifier.isStatic(m)) {
continue;
}
if (Modifier.isPublic(m) || Modifier.isProtected(m)) {
// Is it a "finalize()"?
if(name.equals("finalize") && typeMethod.getParameterCount() == 0) {
if(type != Object.class) {
hasExplicitFinalizer = true;
if(Modifier.isFinal(m)) {
// Must be able to override an explicit finalizer
throw new AdaptationException(Outcome.ERROR_FINAL_FINALIZER, type.getCanonicalName());
}
}
continue;
}
final MethodInfo mi = new MethodInfo(typeMethod);
if (Modifier.isFinal(m) || isCallerSensitive(typeMethod)) {
finalMethods.add(mi);
} else if (!finalMethods.contains(mi) && methodInfos.add(mi)) {
if (Modifier.isAbstract(m)) {
abstractMethodNames.add(mi.getName());
}
mi.setIsCanonical(this);
}
}
}
}
// If the type is a class, visit its superclasses and declared interfaces. If it's an interface, we're done.
// Needing to invoke the method recursively for a non-interface Class object is the consequence of needing to
// see all declared protected methods, and Class.getDeclaredMethods() doesn't provide those declared in a
// superclass. For interfaces, we used Class.getMethods(), as we're only interested in public ones there, and
// getMethods() does provide those declared in a superinterface.
if (!type.isInterface()) {
final Class<?> superType = type.getSuperclass();
if (superType != null) {
gatherMethods(superType);
}
for (final Class<?> itf: type.getInterfaces()) {
gatherMethods(itf);
}
}
}
public static boolean isEndpoint(final Method method) {
final int modifiers = method.getModifiers();
return Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers);
}
public boolean isPublicField(Field field) {
return Modifier.isPublic(field.getModifiers());
}