Java Code Examples for java.lang.reflect.Method#getModifiers()

The following examples show how to use java.lang.reflect.Method#getModifiers() . 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 File: Introspector.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
/**
 * Returns {@code true} if the given method is a "getter" method (where
 * "getter" method is a public method of the form getXXX or "boolean
 * isXXX")
 */
static boolean isReadMethod(Method method) {
    // ignore static methods
    int modifiers = method.getModifiers();
    if (Modifier.isStatic(modifiers))
        return false;

    String name = method.getName();
    Class<?>[] paramTypes = method.getParameterTypes();
    int paramCount = paramTypes.length;

    if (paramCount == 0 && name.length() > 2) {
        // boolean isXXX()
        if (name.startsWith(IS_METHOD_PREFIX))
            return (method.getReturnType() == boolean.class);
        // getXXX()
        if (name.length() > 3 && name.startsWith(GET_METHOD_PREFIX))
            return (method.getReturnType() != void.class);
    }
    return false;
}
 
Example 2
Source File: Injection.java    From ironjacamar with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public int compare(Method o1, Method o2)
{
   int m1 = o1.getModifiers();
   int m2 = o2.getModifiers();

   if (Modifier.isPublic(m1))
      return -1;

   if (Modifier.isPublic(m2))
      return 1;

   if (Modifier.isProtected(m1))
      return -1;

   if (Modifier.isProtected(m2))
      return 1;

   if (Modifier.isPrivate(m1))
      return -1;

   if (Modifier.isPrivate(m2))
      return 1;

   return 0;
}
 
Example 3
Source File: ClassLoaderUtils.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Invoke static void main method from class.
 */
public static Object invokeMainMethodFromClass(Class<?> c, String[] args) throws ClassNotFoundException,
		NoSuchMethodException, InvocationTargetException {
	log.debug("invokeMainMethodFromClass({}, {})", c, args);
	Method m = c.getMethod(MAIN, new Class[]{args.getClass()});
	m.setAccessible(true);
	int mods = m.getModifiers();

	if (m.getReturnType() != void.class || !Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
		throw new NoSuchMethodException(MAIN);
	}

	try {
		return m.invoke(null, new Object[]{args});
	} catch (IllegalAccessException e) {
		// This should not happen, as we have disabled access checks
	}

	return null;
}
 
Example 4
Source File: PropertyDescriptor.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void setReadMethod(Method getter) throws IntrospectionException {
    if (getter != null) {
        int modifiers = getter.getModifiers();
        if (!Modifier.isPublic(modifiers)) {
            throw new IntrospectionException("Modifier for getter method should be public.");
        }
        Class<?>[] parameterTypes = getter.getParameterTypes();
        if (parameterTypes.length != 0) {
            throw new IntrospectionException(
            	"Number of parameters in getter method is not equal to 0.");
        }
        Class<?> returnType = getter.getReturnType();
        if (returnType.equals(Void.TYPE)) {
            throw new IntrospectionException("getter cannot return <void>");
        }
        Class<?> propertyType = getPropertyType();
        if ((propertyType != null) && !returnType.equals(propertyType)) {
            throw new IntrospectionException(
            	"Parameter type in getter method does not corresponds to predefined.");
        }
    }
    this.getter = getter;
}
 
Example 5
Source File: BaseQueueServiceTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
private Map<List<Object>, Method> getDeclaredPublicMethodMap(Class clazz) {
    Map<List<Object>, Method> map = Maps.newHashMap();
    for (Method method : clazz.getDeclaredMethods()) {
        if ((method.getModifiers() & Modifier.PUBLIC) == 0) {
            continue;
        }

        // Compare: name, arg types, return type.  This is similar to Method.equals() except it ignores the declaring class.
        List<Object> signature = ImmutableList.<Object>of(
                method.getName(), ImmutableList.copyOf(method.getParameterTypes()), method.getReturnType());

        Method previous = map.put(signature, method);
        assertNull(previous, method + " collides with " + previous);
    }
    return map;
}
 
Example 6
Source File: ApiTestBase.java    From iaf with Apache License 2.0 6 votes vote down vote up
public void register(M jaxRsResource) {
	Method[] classMethods = jaxRsResource.getClass().getDeclaredMethods();
	for(Method classMethod : classMethods) {
		int modifiers = classMethod.getModifiers();
		if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
			Path path = AnnotationUtils.findAnnotation(classMethod, Path.class);
			HttpMethod httpMethod = AnnotationUtils.findAnnotation(classMethod, HttpMethod.class);
			if(path != null && httpMethod != null) {
				String rsResourceKey = compileKey(httpMethod.value(), path.value());

				System.out.println("adding new JAX-RS resource key ["+rsResourceKey+"] method ["+classMethod.getName()+"]");
				rsRequests.put(rsResourceKey, classMethod);
			}
			//Ignore security for now
		}
	}
}
 
Example 7
Source File: OptionalMethod.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private static Method getPublicMethod(Class<?> clazz, String methodName, Class[] parameterTypes) {
  Method method = null;
  try {
    if (clazz == null) {
      return null;
    }
    if ((clazz.getModifiers() & Modifier.PUBLIC) == 0) {
      return getPublicMethod(clazz.getSuperclass(), methodName, parameterTypes);
    }
    method = clazz.getMethod(methodName, parameterTypes);
    if ((method.getModifiers() & Modifier.PUBLIC) == 0) {
      method = null;
    }
  } catch (NoSuchMethodException e) {
    // None.
  }
  return method;
}
 
Example 8
Source File: ObjectStreamClass.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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).
 *
 * Copied from the Merlin java.io.ObjectStreamClass.
 */
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;
    }
}
 
Example 9
Source File: SubscriberHandlerFinder.java    From divide with Apache License 2.0 5 votes vote down vote up
private static void loadProducers(Class<?> listenerClass) {
    Map<Class<?>, Method> producerMethods = new HashMap<Class<?>, Method>();

    for (Method method : listenerClass.getDeclaredMethods()) {
        if (method.isAnnotationPresent(Produce.class)) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length != 0) {
                throw new IllegalArgumentException("Method " + method + "has @Produce annotation but requires "
                        + parameterTypes.length + " arguments.  Methods must require zero arguments.");
            }
            if (method.getReturnType() == Void.class) {
                throw new IllegalArgumentException("Method " + method
                        + " has a return type of void.  Must declare a non-void type.");
            }

            Class<?> eventType = method.getReturnType();
            if (eventType.isInterface()) {
                throw new IllegalArgumentException("Method " + method + " has @Produce annotation on " + eventType
                        + " which is an interface.  Producers must return a concrete class type.");
            }
            if (eventType.equals(Void.TYPE)) {
                throw new IllegalArgumentException("Method " + method + " has @Produce annotation but has no return type.");
            }

            if ((method.getModifiers() & Modifier.PUBLIC) == 0) {
                throw new IllegalArgumentException("Method " + method + " has @Produce annotation on " + eventType
                        + " but is not 'public'.");
            }

            if (producerMethods.containsKey(eventType)) {
                throw new IllegalArgumentException("Producer for type " + eventType + " has already been registered.");
            }
            producerMethods.put(eventType, method);
        }
    }

    PRODUCERS_CACHE.put(listenerClass, producerMethods);
}
 
Example 10
Source File: AdvancedProxy.java    From consulo with Apache License 2.0 5 votes vote down vote up
public int accept(Method method) {
  if (AdvancedProxy.FINALIZE_METHOD.equals(method)) {
    return 1;
  }

  if ((method.getModifiers() & Modifier.ABSTRACT) != 0) {
    return 0;
  }

  return 1;
}
 
Example 11
Source File: KernelLoader.java    From swim with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Kernel loadKernelModule(ClassLoader classLoader, Value moduleConfig) {
  Kernel kernel = null;
  final Value header = moduleConfig.getAttr("kernel");
  final String kernelClassName = header.get("class").stringValue(null);
  if (kernelClassName != null) {
    try {
      final Class<? extends Kernel> kernelClass = (Class<? extends Kernel>) Class.forName(kernelClassName, true, classLoader);
      try {
        final Method kernelFromValueMethod = kernelClass.getMethod("fromValue", Value.class);
        if ((kernelFromValueMethod.getModifiers() & Modifier.STATIC) != 0) {
          kernelFromValueMethod.setAccessible(true);
          kernel = (Kernel) kernelFromValueMethod.invoke(null, moduleConfig);
        }
      } catch (NoSuchMethodException swallow) {
        // continue
      }
      if (kernel == null) {
        final Constructor<? extends Kernel> kernelConstructor = kernelClass.getConstructor();
        kernelConstructor.setAccessible(true);
        kernel = kernelConstructor.newInstance();
      }
    } catch (ReflectiveOperationException cause) {
      if (!header.get("optional").booleanValue(false)) {
        throw new KernelException("failed to load required kernel class: " + kernelClassName, cause);
      }
    }
  }
  return kernel;
}
 
Example 12
Source File: AdvancedEnhancer.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean isJdk8DefaultMethod(Method method) {
  // FIXME [VISTALL] give logic to cglib
  if(Boolean.FALSE) {
    return ((method.getModifiers() & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) == Modifier.PUBLIC) && method.getDeclaringClass().isInterface();
  }
  return false;
}
 
Example 13
Source File: TestPBImplRecords.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * this method generate record instance by calling newIntance
 * using reflection, add register the generated value to typeValueCache
 */
@SuppressWarnings("rawtypes")
private static Object generateByNewInstance(Class clazz) throws Exception {
  Object ret = typeValueCache.get(clazz);
  if (ret != null) {
    return ret;
  }
  Method newInstance = null;
  Type [] paramTypes = new Type[0];
  // get newInstance method with most parameters
  for (Method m : clazz.getMethods()) {
    int mod = m.getModifiers();
    if (m.getDeclaringClass().equals(clazz) &&
        Modifier.isPublic(mod) &&
        Modifier.isStatic(mod) &&
        m.getName().equals("newInstance")) {
      Type [] pts = m.getGenericParameterTypes();
      if (newInstance == null
          || (pts.length > paramTypes.length)) {
        newInstance = m;
        paramTypes = pts;
      }
    }
  }
  if (newInstance == null) {
    throw new IllegalArgumentException("type " + clazz.getName() +
        " does not have newInstance method");
  }
  Object [] args = new Object[paramTypes.length];
  for (int i=0;i<args.length;i++) {
    args[i] = genTypeValue(paramTypes[i]);
  }
  ret = newInstance.invoke(null, args);
  typeValueCache.put(clazz, ret);
  return ret;
}
 
Example 14
Source File: ReflectionFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Lookup readResolve or writeReplace on a class with specified
 * signature constraints.
 * @param cl a serializable class
 * @param methodName the method name to find
 * @returns a MethodHandle for the method or {@code null} if not found or
 *       has the wrong signature.
 */
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;
}
 
Example 15
Source File: SchemaManager.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Registers SQL functions.
 *
 * @param schema Schema.
 * @param clss Classes.
 * @throws IgniteCheckedException If failed.
 */
private void createSqlFunctions(String schema, Class<?>[] clss) throws IgniteCheckedException {
    if (F.isEmpty(clss))
        return;

    for (Class<?> cls : clss) {
        for (Method m : cls.getDeclaredMethods()) {
            QuerySqlFunction ann = m.getAnnotation(QuerySqlFunction.class);

            if (ann != null) {
                int modifiers = m.getModifiers();

                if (!Modifier.isStatic(modifiers) || !Modifier.isPublic(modifiers))
                    throw new IgniteCheckedException("Method " + m.getName() + " must be public static.");

                String alias = ann.alias().isEmpty() ? m.getName() : ann.alias();

                String clause = "CREATE ALIAS IF NOT EXISTS " + alias + (ann.deterministic() ?
                    " DETERMINISTIC FOR \"" :
                    " FOR \"") +
                    cls.getName() + '.' + m.getName() + '"';

                connMgr.executeStatement(schema, clause);
            }
        }
    }
}
 
Example 16
Source File: SubscriberHandlerFinder.java    From divide with Apache License 2.0 5 votes vote down vote up
private static void loadSubscribers(Class<?> listenerClass) {
    Map<Class<?>, Set<Method>> subscriberMethods = new HashMap<Class<?>, Set<Method>>();

    if(!isSubscriberClass(listenerClass))return; // no need checking this for each method...

    for (Method method : listenerClass.getDeclaredMethods()) {
        if (isSubscriberMethod(method)) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length != 1) {
                throw new IllegalArgumentException("Method " + method + " has @Subscribe annotation but requires "
                        + parameterTypes.length + " arguments.  Methods must require a single argument.");
            }

            Class<?> eventType = parameterTypes[0];
            if (eventType.isInterface()) {
                throw new IllegalArgumentException("Method " + method + " has @Subscribe annotation on " + eventType
                        + " which is an interface.  Subscription must be on a concrete class type.");
            }

            if ((method.getModifiers() & Modifier.PUBLIC) == 0) {
                throw new IllegalArgumentException("Method " + method + " has @Subscribe annotation on " + eventType
                        + " but is not 'public'.");
            }

            System.out.println("EventType: " + eventType);
            Set<Method> methods = subscriberMethods.get(eventType);
            if (methods == null) {
                methods = new HashSet<Method>();
                subscriberMethods.put(eventType, methods);
            }
            methods.add(method);
        }
    }

    SUBSCRIBERS_CACHE.put(listenerClass, subscriberMethods);
}
 
Example 17
Source File: Msc.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static Class<?> getCallingMainClass() {
	StackTraceElement[] trace = Thread.currentThread().getStackTrace();

	// skip the first 2 elements:
	// [0] java.lang.Thread.getStackTrace
	// [1] THIS METHOD

	for (int i = 2; i < trace.length; i++) {
		String cls = trace[i].getClassName();

		if (couldBeCaller(cls) && U.eq(trace[i].getMethodName(), "main")) {
			Class<?> clazz = Cls.getClassIfExists(cls);

			if (clazz != null) {
				Method main = Cls.findMethod(clazz, "main", String[].class);
				if (main != null && main.getReturnType() == void.class
					&& !main.isVarArgs() && main.getDeclaringClass().equals(clazz)) {
					int modif = main.getModifiers();
					if (Modifier.isStatic(modif) && Modifier.isPublic(modif)) {
						return clazz;
					}
				}
			}
		}
	}

	return null;
}
 
Example 18
Source File: TestGetAnnotationElements.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 19
Source File: CompiledClassUtils.java    From Concurnas with MIT License 4 votes vote down vote up
public static Map<String, HashSet<TypeAndLocation>> getAllMethods(Class<?> relevantClass, Map<String, GenericType> nameToGenericMap, boolean publicOnly)
{//non static, public methods
	Map<String, HashSet<TypeAndLocation>> ret = new HashMap<String, HashSet<TypeAndLocation>>();
	
	HashSet<MethodHolder> methods = getAllMethods(relevantClass);
	if(!methods.isEmpty()){

		ClassDefJava clsDef = new ClassDefJava(relevantClass);
		NamedType ownerNt = new NamedType(clsDef);
		
		for(MethodHolder mh : methods){
			Method m = mh.held;
			int modifiders =  m.getModifiers();
			String name = m.getName();
							
			boolean isPublic = !publicOnly || Modifier.isPublic(modifiders);
			
			if(isPublic && !Modifier.isStatic(modifiders) && !name.equals("<init>") && isValidMethod(m.getParameters()) ){
				FuncType sig = convertMethodToFuncType(m, nameToGenericMap);
				boolean callable=true;
				if(UncallableMethods.GLOBAL_UNCALLABLE_METHODS.containsKey(name)  )
				{
					//this method is not callable in concurnas
					for(FuncType can : UncallableMethods.GLOBAL_UNCALLABLE_METHODS.get(name))
					{
						if(can.equals(sig))
						{
							callable = false;
							break;
						}
					}
				}
				if(callable){//remove notify etc
					String bcName = clsDef.bcFullName();
											
					HashSet<TypeAndLocation> got = ret.get(name);
					if(got == null){
						got = new HashSet<TypeAndLocation>();
						ret.put(name, got);
					}
					got.add(new TypeAndLocation(sig, new ClassFunctionLocation(bcName, ownerNt)));
				}
			}
		}
	}
	
	return ret;
}
 
Example 20
Source File: BeanUtil.java    From framework with Apache License 2.0 2 votes vote down vote up
/**
 * 判断方法是否是抽象方法
 * 
 * @param method <br>
 * @return <br>
 */
public static boolean isAbstract(final Method method) {
    int mod = method.getModifiers();
    return Modifier.isAbstract(mod);
}