How do I pass a class as a parameter in Java?

后端 未结 10 1153
遥遥无期
遥遥无期 2020-12-04 08:30

Is there any way to pass class as a parameter in Java and fire some methods from that class?

void main()
{
    callClass(that.class)
}

void callClass(???? c         


        
10条回答
  •  情深已故
    2020-12-04 09:36

    This kind of thing is not easy. Here is a method that calls a static method:

    public static Object callStaticMethod(
        // class that contains the static method
        final Class clazz,
        // method name
        final String methodName,
        // optional method parameters
        final Object... parameters) throws Exception{
        for(final Method method : clazz.getMethods()){
            if(method.getName().equals(methodName)){
                final Class[] paramTypes = method.getParameterTypes();
                if(parameters.length != paramTypes.length){
                    continue;
                }
                boolean compatible = true;
                for(int i = 0; i < paramTypes.length; i++){
                    final Class paramType = paramTypes[i];
                    final Object param = parameters[i];
                    if(param != null && !paramType.isInstance(param)){
                        compatible = false;
                        break;
                    }
    
                }
                if(compatible){
                    return method.invoke(/* static invocation */null,
                        parameters);
                }
            }
        }
        throw new NoSuchMethodException(methodName);
    }
    

    Update: Wait, I just saw the gwt tag on the question. You can't use reflection in GWT

提交回复
热议问题