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

后端 未结 10 1159
遥遥无期
遥遥无期 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条回答
  •  猫巷女王i
    2020-12-04 09:26

    public void foo(Class c){
            try {
                Object ob = c.newInstance();
            } catch (InstantiationException ex) {
                Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    
    • Here are some good examples on Reflection API

    How to invoke method using reflection

     import java.lang.reflect.*;
    
    
       public class method2 {
          public int add(int a, int b)
          {
             return a + b;
          }
    
          public static void main(String args[])
          {
             try {
               Class cls = Class.forName("method2");
               Class partypes[] = new Class[2];
                partypes[0] = Integer.TYPE;
                partypes[1] = Integer.TYPE;
                Method meth = cls.getMethod(
                  "add", partypes);
                method2 methobj = new method2();
                Object arglist[] = new Object[2];
                arglist[0] = new Integer(37);
                arglist[1] = new Integer(47);
                Object retobj 
                  = meth.invoke(methobj, arglist);
                Integer retval = (Integer)retobj;
                System.out.println(retval.intValue());
             }
             catch (Throwable e) {
                System.err.println(e);
             }
          }
       }
    

    Also See

    • Java Reflection

提交回复
热议问题