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

前端 未结 5 894
悲哀的现实
悲哀的现实 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 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 obj)
    {
      return obj.newInstance();
    }
    

提交回复
热议问题