如何在Java中将类作为参数传递?

123 java parameters gwt class

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

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

void callClass(???? classObject)
{
    classObject.somefunction
    // or 
    new classObject()
    //something like that ?
}
Run Code Online (Sandbox Code Playgroud)

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

Jig*_*shi 118

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

如何使用反射调用方法

 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);
         }
      }
   }
Run Code Online (Sandbox Code Playgroud)

另见


Ola*_*eph 38

public void callingMethod(Class neededClass) {
    //Cast the class to the class you need
    //and call your method in the class
    ((ClassBeingCalled)neededClass).methodOfClass();
}
Run Code Online (Sandbox Code Playgroud)

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

callingMethod(ClassBeingCalled.class);
Run Code Online (Sandbox Code Playgroud)


Jos*_*ney 13

构建你的方法来接受它-

public <T> void printClassNameAndCreateList(Class<T> className){
    //example access 1
    System.out.print(className.getName());

    //example access 2
    ArrayList<T> list = new ArrayList<T>();
    //note that if you create a list this way, you will have to cast input
    list.add((T)nameOfObject);
}
Run Code Online (Sandbox Code Playgroud)

调用方法-

printClassNameAndCreateList(SomeClass.class);
Run Code Online (Sandbox Code Playgroud)

您还可以限制类的类型,例如,这是我制作的库中的方法之一-

protected Class postExceptionActivityIn;

protected <T extends PostExceptionActivity>  void  setPostExceptionActivityIn(Class <T> postExceptionActivityIn) {
    this.postExceptionActivityIn = postExceptionActivityIn;
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请搜索反射和泛型。