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

前端 未结 5 882
悲哀的现实
悲哀的现实 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> C getObject(Class<C> c) throws Exception 
    { 
        return c.newInstance(); 
    }
    

    Usage Example:

    static <C> C getObject(Class<C> 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();
    }
    
    0 讨论(0)
  • 2020-12-10 12:58

    I assume you want to create a new instance of that class. This would not be possible using generics (you can't call new T()) and would also be quite limited using reflection.

    The reflection approach could be:

    //class is a reserved word, so use clazz
    public <T> T getObject(Class<T> clazz) {
      try {
        return clazz.newInstance();
      }
      catch( /*a multitude of exceptions that can be thrown by clazz.newInstance()*/ ) {
        //handle exception
      }
    }
    

    Note that this only works if the class has a no-argument constructor.

    However, the question would by why you need that instead of just calling
    new WhatEverClassYouHave().

    0 讨论(0)
  • 2020-12-10 12:58
    public Object getObject(Class clazz) {
      return clazz.newInstance();
    }
    

    Will create a new object of the specified class. You don't have to use generics for this.

    0 讨论(0)
  • 2020-12-10 13:00

    You don't have to implement this method, it's already there:

    http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#newInstance%28%29

    Usage:

    Class<T> type = ...;
    T instance = type.newInstance();
    
    0 讨论(0)
  • 2020-12-10 13:01

    If you aren't trying to do anything fancy with the object during the creation, what's wrong with just using a good old fashioned constructors?

    You should be able to use something similar to:

    public T getObject<T>(T obj)
    {
      return obj.newInstance();
    }
    
    0 讨论(0)
提交回复
热议问题