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

后端 未结 10 1117
遥遥无期
遥遥无期 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:28

    Se these: http://download.oracle.com/javase/tutorial/extra/generics/methods.html

    here is the explaniation for the template methods.

    0 讨论(0)
  • 2020-12-04 09:31

    Have a look at the reflection tutorial and reflection API of Java:

    https://community.oracle.com/docs/DOC-983192enter link description here

    and

    http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html

    0 讨论(0)
  • 2020-12-04 09:32

    Class as paramater. Example.

    Three classes:

    class TestCar {
    
        private int UnlockCode = 111;
        protected boolean hasAirCondition = true;
        String brand = "Ford";
        public String licensePlate = "Arizona 111";
    }
    

    --

    class Terminal {
    
    public void hackCar(TestCar car) {
         System.out.println(car.hasAirCondition);
         System.out.println(car.licensePlate);
         System.out.println(car.brand);
         }
    }
    

    --

    class Story {
    
        public static void main(String args[]) {
            TestCar testCar = new TestCar();
            Terminal terminal = new Terminal();
            terminal.hackCar(testCar);
        }
    
    }
    

    In class Terminal method hackCar() take class TestCar as parameter.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题