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

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

    Construct your method to accept it-

    public  void printClassNameAndCreateList(Class className){
        //example access 1
        System.out.print(className.getName());
    
        //example access 2
        ArrayList list = new ArrayList();
        //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   void  setPostExceptionActivityIn(Class  postExceptionActivityIn) {
        this.postExceptionActivityIn = postExceptionActivityIn;
    }
    

    For more information, search Reflection and Generics.

提交回复
热议问题