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

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

    Use

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

    A Class is also a Java object, so you can refer to it by using its type.

    Read more about it from official documentation.

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

    I am not sure what you are trying to accomplish, but you may want to consider that passing a class may not be what you really need to be doing. In many cases, dealing with Class like this is easily encapsulated within a factory pattern of some type and the use of that is done through an interface. here's one of dozens of articles on that pattern: http://today.java.net/pub/a/today/2005/03/09/factory.html

    using a class within a factory can be accomplished in a variety of ways, most notably by having a config file that contains the name of the class that implements the required interface. Then the factory can find that class from within the class path and construct it as an object of the specified interface.

    0 讨论(0)
  • 2020-12-04 09:23
    public void callingMethod(Class neededClass) {
        //Cast the class to the class you need
        //and call your method in the class
        ((ClassBeingCalled)neededClass).methodOfClass();
    }
    

    To call the method, you call it this way:

    callingMethod(ClassBeingCalled.class);
    
    0 讨论(0)
  • 2020-12-04 09:25

    Construct your method to accept it-

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

    Call the method-

    printClassNameAndCreateList(SomeClass.class);
    

    You can also restrict the type of class, for example, this is one of the methods from a library I made-

    protected Class postExceptionActivityIn;
    
    protected <T extends PostExceptionActivity>  void  setPostExceptionActivityIn(Class <T> postExceptionActivityIn) {
        this.postExceptionActivityIn = postExceptionActivityIn;
    }
    

    For more information, search Reflection and Generics.

    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-12-04 09:26

    As you said GWT does not support reflection. You should use deferred binding instead of reflection, or third party library such as gwt-ent for reflection suppport at gwt layer.

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