How do I return an instance of an object of the same type as the class passed in using Java 6?

前端 未结 5 884
悲哀的现实
悲哀的现实 2020-12-10 12:14

I want to return an instance of an object of same type of the Class object passed in. The type passed in can be ANYTHING. Is there a way to do this with Generics?

To

5条回答
  •  [愿得一人]
    2020-12-10 12:55

    public  C getObject(Class c) throws Exception 
    { 
        return c.newInstance(); 
    }
    

    Usage Example:

    static  C getObject(Class c) throws Exception { 
        return c.newInstance();
    }
    
    static class Testing {
        {System.out.println("Instantiated");}
        void identify(){ System.out.println("Invoked"); }
    }
    
    public static void main(String args[]) throws Exception {
        Testing t = getObject(Testing.class);
        t.identify();
    }
    

提交回复
热议问题