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 clarify -- I don't want the caller of the method to not have to cast to the Class of the object they passed in
For example,
public Object<Class> getObject(Class class)
{
// Construct an instance of an object of type Class
return object;
}
// I want this:
MyClass myObj = getObject(MyClass.class);
// Not this (casting):
MyClass myObj = (MyClass)getObject(MyClass.class);
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:
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:
Will create a new object of the specified class. You don't have to use generics for this.
Usage Example:
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:
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()
.