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

The following are Jave code examples for showing how to use getModifiers() of the java.lang.reflect.Method class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: openjdk-jdk10   File: ReflectionFactory.java   View Source Code Vote up 6 votes
private final MethodHandle findReadWriteObjectForSerialization(Class<?> cl,
                                                               String methodName,
                                                               Class<?> streamClass) {
    if (!Serializable.class.isAssignableFrom(cl)) {
        return null;
    }

    try {
        Method meth = cl.getDeclaredMethod(methodName, streamClass);
        int mods = meth.getModifiers();
        if (meth.getReturnType() != Void.TYPE ||
                Modifier.isStatic(mods) ||
                !Modifier.isPrivate(mods)) {
            return null;
        }
        meth.setAccessible(true);
        return MethodHandles.lookup().unreflect(meth);
    } catch (NoSuchMethodException ex) {
        return null;
    } catch (IllegalAccessException ex1) {
        throw new InternalError("Error", ex1);
    }
}
 
Example 2
Project: openjdk-jdk10   File: ObjectStreamClass.java   View Source Code Vote up 6 votes
/**
 * Returns non-static private method with given signature defined by given
 * class, or null if none found.  Access checks are disabled on the
 * returned method (if any).
 */
private static Method getPrivateMethod(Class<?> cl, String name,
                                       Class<?>[] argTypes,
                                       Class<?> returnType)
{
    try {
        Method meth = cl.getDeclaredMethod(name, argTypes);
        meth.setAccessible(true);
        int mods = meth.getModifiers();
        return ((meth.getReturnType() == returnType) &&
                ((mods & Modifier.STATIC) == 0) &&
                ((mods & Modifier.PRIVATE) != 0)) ? meth : null;
    } catch (NoSuchMethodException ex) {
        return null;
    }
}
 
Example 3
Project: HtmlNative   File: LuajavaLib.java   View Source Code Vote up 6 votes
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	String name = method.getName();
	LuaValue func = lobj.get(name);
	if ( func.isnil() )
		return null;
	boolean isvarargs = ((method.getModifiers() & METHOD_MODIFIERS_VARARGS) != 0);
	int n = args!=null? args.length: 0; 
	LuaValue[] v;
	if ( isvarargs ) {								
		Object o = args[--n];
		int m = Array.getLength( o );
		v = new LuaValue[n+m];
		for ( int i=0; i<n; i++ )
			v[i] = CoerceJavaToLua.coerce(args[i]);
		for ( int i=0; i<m; i++ )
			v[i+n] = CoerceJavaToLua.coerce(Array.get(o,i));								
	} else {
		v = new LuaValue[n];
		for ( int i=0; i<n; i++ )
			v[i] = CoerceJavaToLua.coerce(args[i]);
	}
	LuaValue result = func.invoke(v).arg1();
	return CoerceLuaToJava.coerce(result, method.getReturnType());
}
 
Example 4
Project: Cubes_2   File: LuaClass.java   View Source Code Vote up 6 votes
private LuaMethod luaTableTry(String s){
	try {
		Method[] methods = c.getMethods();
		ArrayList<Method> validMethods = new ArrayList<Method>();
		for (Method method : methods) {
			int modifiers = method.getModifiers();
			if (Modifier.isStatic(modifiers) && method.getAnnotation(LuaExclude.class) == null
					&& method.getName().equals(s)) {
				validMethods.add(method);
			}
		}
		if (validMethods.size() > 0)
			return new LuaMethod(validMethods, c, s);
	} catch (Exception ignored) {
	}
}
 
Example 5
Project: openjdk-jdk10   File: ServerMain.java   View Source Code Vote up 6 votes
private boolean isPublicStaticVoid( Method method )
{
    // check modifiers: public static
    int modifiers =  method.getModifiers ();
    if (!Modifier.isPublic (modifiers) || !Modifier.isStatic (modifiers)) {
        logError( method.getName() + " is not public static" ) ;
        return false ;
    }

    // check return type and exceptions
    if (method.getExceptionTypes ().length != 0) {
        logError( method.getName() + " declares exceptions" ) ;
        return false ;
    }

    if (!method.getReturnType().equals (Void.TYPE)) {
        logError( method.getName() + " does not have a void return type" ) ;
        return false ;
    }

    return true ;
}
 
Example 6
Project: openjdk-jdk10   File: Introspector.java   View Source Code Vote up 6 votes
/**
 * 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 7
Project: tangyuan2   File: TypeUtils.java   View Source Code Vote up 6 votes
private static boolean checkGetter(Method method) {
	int modifiers = method.getModifiers();
	if (Modifier.isStatic(modifiers)) {
		return true;
	}
	if (Modifier.isNative(modifiers)) {
		return true;
	}
	if (Modifier.isAbstract(modifiers)) {
		return true;
	}
	if (method.getReturnType().equals(Void.TYPE)) {
		return true;
	}
	if (method.getParameterTypes().length != 0) {
		return true;
	}
	if (method.getReturnType() == ClassLoader.class) {
		return true;
	}
	if (method.getName().equals("getClass")) {
		return true;
	}
	return false;
}
 
Example 8
Project: Pogamut3   File: ParamsMethod.java   View Source Code Vote up 6 votes
/**
 * Filter all methods to ensure following conditions:
 *
 * <ul><li>Method name is @name</li>
 *
 * <li>Method is <tt>public<tt></li>
 *
 * <li>Method is not <tt>abstract</tt></li>.
 *
 * <li>Method does not have variable number of arguments</li>
 *
 * <li>Return type of method is @returnType</li>
 *
 * <li>All parameter fields are of type {@link String}, {@link Integer} or {@link Double}</li>
 *
 * <li>All parameters are annotated with {@link Param}</li> </ul>
 *
 * @param methods Array of methods to be filtered.
 * @param seekedName Name of the methods we are looking for.
 * @param returnType Expected return type of filtered methods.
 * @return Array of methods with @name.
 */
private Method[] filterMethods(Method[] methods, String seekedName, Class<?> returnType) {
    List<Method> filteredMethods = new LinkedList<Method>();

    for (Method testedMethod : methods) {
        String testedMethodName = testedMethod.getName();
        boolean methodIsPublic = (testedMethod.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC;
        boolean methodIsAbstract = (testedMethod.getModifiers() & Modifier.ABSTRACT) == Modifier.ABSTRACT;
        boolean correctReturnType = returnType.isAssignableFrom(testedMethod.getReturnType());
        boolean acceptedParams = areParamsAcceptable(testedMethod, true, allowedParamClasses);
        boolean annotatedParams = areParamsAnnotated(testedMethod);

        if (testedMethodName.equals(seekedName)
                && methodIsPublic
                && !methodIsAbstract
                && !testedMethod.isVarArgs()
                && correctReturnType
                && acceptedParams
                && annotatedParams) {
            filteredMethods.add(testedMethod);
        }
    }
    return filteredMethods.toArray(new Method[filteredMethods.size()]);
}
 
Example 9
Project: SurvivalAPI   File: NbtFactory.java   View Source Code Vote up 6 votes
/**
 * Search for the first publically and privately defined method of the given name and parameter count.
 * @param requireMod - modifiers that are required.
 * @param bannedMod - modifiers that are banned.
 * @param clazz - a class to start with.
 * @param methodName - the method name, or NULL to skip.
 * @param params - the expected parameters.
 * @return The first method by this name.
 * @throws IllegalStateException If we cannot find this method.
 */
private static Method getMethod(int requireMod, int bannedMod, Class<?> clazz, String methodName, Class<?>... params) {
    for (Method method : clazz.getDeclaredMethods()) {
        // Limitation: Doesn't handle overloads
        if ((method.getModifiers() & requireMod) == requireMod &&
                (method.getModifiers() & bannedMod) == 0 &&
                (methodName == null || method.getName().equals(methodName)) &&
                Arrays.equals(method.getParameterTypes(), params)) {

            method.setAccessible(true);
            return method;
        }
    }
    // Search in every superclass
    if (clazz.getSuperclass() != null)
        return getMethod(requireMod, bannedMod, clazz.getSuperclass(), methodName, params);
    throw new IllegalStateException(String.format(
            "Unable to find method %s (%s).", methodName, Arrays.asList(params)));
}
 
Example 10
Project: businessworks   File: InjectionPoint.java   View Source Code Vote up 5 votes
/**
 * Returns true if a overrides b. Assumes signatures of a and b are the same and a's declaring
 * class is a subclass of b's declaring class.
 */
private static boolean overrides(Method a, Method b) {
  // See JLS section 8.4.8.1
  int modifiers = b.getModifiers();
  if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
    return true;
  }
  if (Modifier.isPrivate(modifiers)) {
    return false;
  }
  // b must be package-private
  return a.getDeclaringClass().getPackage().equals(b.getDeclaringClass().getPackage());
}
 
Example 11
Project: businessworks   File: ProviderMethodsModule.java   View Source Code Vote up 5 votes
/** Returns true if a overrides b, assumes that the signatures match */
private static boolean overrides(Method a, Method b) {
  // See JLS section 8.4.8.1
  int modifiers = b.getModifiers();
  if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
    return true;
  }
  if (Modifier.isPrivate(modifiers)) {
    return false;
  }
  // b must be package-private
  return a.getDeclaringClass().getPackage().equals(b.getDeclaringClass().getPackage());
}
 
Example 12
Project: LuaViewPlayground   File: BaseVarArgCreator.java   View Source Code Vote up 5 votes
private void getMapperMethodsByClazz(final List<Method> result, final Class clazz) {
    if (clazz != null && clazz.isAnnotationPresent(LuaViewLib.class)) {//XXXMapper
        getMapperMethodsByClazz(result, clazz.getSuperclass());//处理super
        final Method[] methods = clazz.getDeclaredMethods();
        if (methods != null && methods.length > 0) {
            for (final Method method : methods) {//add self
                if (method.getModifiers() == Modifier.PUBLIC) {//public 方法才行
                    result.add(method);
                }
            }
        }
    }
}
 
Example 13
Project: lams   File: MockHelper.java   View Source Code Vote up 5 votes
private static MethodInfo getMethodInfo(ClassInfo classInfo, Method method) {
	Class returnTypeClass = method.getReturnType();
	short access_flags = (short) method.getModifiers();
	return MethodInfo.create(
			classInfo,
			method.getName(),
			getTypes( method.getParameterTypes() ),
			getType( returnTypeClass ),
			access_flags
	);
}
 
Example 14
Project: LuaViewPlayground   File: JavaMethod.java   View Source Code Vote up 5 votes
private JavaMethod(Method m) {
	super( m.getParameterTypes(), m.getModifiers() ); //TODO 这里需要保护, m.getParameterTypes报错
	this.method = m;
	try {
		if (!m.isAccessible())
			m.setAccessible(true);
	} catch (SecurityException s) {
	}
}
 
Example 15
Project: solo-spring   File: Reflections.java   View Source Code Vote up 5 votes
public static boolean matchInheritance(final Method subclassMethod, final Method superclassMethod) {
	if (Modifier.isStatic(superclassMethod.getModifiers()) || subclassMethod.equals(superclassMethod)) {
		return false;
	}

	if (matchSignature(subclassMethod, superclassMethod)) {
		final Package subclassPackage = subclassMethod.getDeclaringClass().getPackage();
		final Package superclassPackage = superclassMethod.getDeclaringClass().getPackage();
		final int superMethodModifiers = superclassMethod.getModifiers();

		return isAccessable(subclassPackage, superclassPackage, superMethodModifiers);
	} else {
		return false;
	}
}
 
Example 16
Project: saluki   File: ClassUtils.java   View Source Code Vote up 5 votes
/**
 * Get all public, non-static methods of the Class passed in.
 *
 * @param clazz
 *            Class to parse.
 * @return methods list
 */
public static List<Method> getPublicMethods(final Class<?> clazz) {
    List<Method> result = new ArrayList<Method>();

    Method[] methods = clazz.getMethods();
    for (Method method : methods) {
        int mod = method.getModifiers();
        if (Modifier.isPublic(mod)) {
            result.add(method);
        }
    }
    return result;
}
 
Example 17
Project: myfaces-trinidad   File: JavaIntrospector.java   View Source Code Vote up 4 votes
/**
 * Internal support for finding a target methodName on a given class.
 */
// -= Simon Lessard
// FIXME: Never used locally
@SuppressWarnings("unused")
private static Method _internalFindMethod(
  Class<?> start,
  String   methodName,
  int      argCount
  )
{
  // For overriden methods we need to find the most derived version.
  // So we start with the given class and walk up the superclass chain.
  for (Class<?> cl = start; cl != null; cl = cl.getSuperclass())
  {
    Method methods[] = _getPublicMethods(cl);

    for (int i = 0; i < methods.length; i++)
    {
      Method method = methods[i];

      // skip static and non-public methods.
      int mods = method.getModifiers();

      if (Modifier.isStatic(mods) || !Modifier.isPublic(mods))
      {
        continue;
      }

      if (method.getName().equals(methodName) &&
          (method.getParameterTypes().length == argCount))
      {
        return method;
      }
    }
  }

  // Now check any inherited interfaces.  This is necessary both when
  // the argument class is itself an interface, and when the argument
  // class is an abstract class.
  Class ifcs[] = start.getInterfaces();

  for (int i = 0 ; i < ifcs.length; i++)
  {
    Method m = _internalFindMethod(ifcs[i], methodName, argCount);

    if (m != null)
    {
      return m;
    }
  }

  return null;
}
 
Example 18
Project: MMORPG_Prototype   File: GameCommandsHandler.java   View Source Code Vote up 4 votes
private boolean isPublic(Method method)
{
	final int access = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE;
	return (method.getModifiers() & access) == Modifier.PUBLIC;
}
 
Example 19
Project: OpenJSharp   File: JavaAdapterBytecodeGenerator.java   View Source Code Vote up 4 votes
/**
 * 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);
        }
    }
}
 
Example 20
Project: sstore-soft   File: Routine.java   View Source Code Vote up 4 votes
static Method[] getMethods(String name) {

        int i = name.lastIndexOf('.');

        if (i == -1) {
            throw Error.error(ErrorCode.X_42501, name);
        }

        String classname     = name.substring(0, i);
        String methodname    = name.substring(i + 1);
        Class  classinstance = null;

        try {
            classinstance = Class.forName(classname);
        } catch (Exception e) {
            throw Error.error(ErrorCode.X_42501, ErrorCode.M_Message_Pair,
                              new Object[] {
                classname, e
            });
        }

        Method[]      methods = classinstance.getMethods();
        HsqlArrayList list    = new HsqlArrayList();

        for (i = 0; i < methods.length; i++) {
            int    offset    = 0;
            Method m         = methods[i];
            int    modifiers = m.getModifiers();

            if (!m.getName().equals(methodname)
                    || !Modifier.isStatic(modifiers)
                    || !Modifier.isPublic(modifiers)) {
                continue;
            }

            Class[] params = methods[i].getParameterTypes();

            if (params.length > 0
                    && params[0].equals(java.sql.Connection.class)) {
                offset = 1;
            }

            for (int j = offset; j < params.length; j++) {
                Class param = params[j];
                Type methodParamType = Type.getDefaultTypeWithSize(
                    Types.getParameterSQLTypeNumber(param));

                if (methodParamType == null) {
                    m = null;

                    break;
                }
            }

            if (m == null) {
                continue;
            }

            Type methodReturnType = Type.getDefaultTypeWithSize(
                Types.getParameterSQLTypeNumber(m.getReturnType()));

            if (methodReturnType != null) {
                list.add(methods[i]);
            }
        }

        methods = new Method[list.size()];

        list.toArray(methods);

        return methods;
    }