问题

有没有办法在Java中将类作为参数传递并从该类中激活一些方法?

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

void callClass(???? classObject)
{
    classObject.somefunction
    // or 
    new classObject()
    //something like that ?
}

我使用的是Google Web Toolkit,它不支持反射。


#1 热门回答(94 赞)

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);
        }
    }

-以下是Reflection API的一些很好的例子

如何使用反射调用方法

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);
         }
      }
   }

另见- Java反射


#2 热门回答(33 赞)

public void callingMethod(Class neededClass) {
    //Put your codes here
}

要调用该方法,请按以下方式调用它:

callingMethod(ClassBeingCalled.class);

#3 热门回答(4 赞)

使用

void callClass(Class classObject)
{
   //do something with class
}

AClass也是一个Java对象,因此你可以使用其类型来引用它。

official documentation了解更多信息。


原文链接