I would like to create an object of Generics Type in java. Please suggest how can I achieve the same.
Note: This may seem a trivial Generics Problem. But I bet.. it isn't. :)
suppose I have the class declaration as:
public class Abc<T> {
public T getInstanceOfT() {
// I want to create an instance of T and return the same.
}
}
There are hacky ways around this when you really have to do it.
Here's an example of a transform method that I find very useful; and provides one way to determine the concrete class of a generic.
This method accepts a collection of objects as input, and returns an array where each element is the result of calling a field getter on each object in the input collection. For example, say you have a
List<People>
and you want aString[]
containing everyone's last name.The type of the field value returned by the getter is specified by the generic
E
, and I need to instantiate an array of typeE[]
to store the return value.The method itself is a bit ugly, but the code you write that uses it can be so much cleaner.
Note that this technique only works when somewhere in the input arguments there is an object whose type matches the return type, and you can deterministically figure it out. If the concrete classes of your input parameters (or their sub-objects) can tell you nothing about the generics, then this technique won't work.
Full code is here: https://github.com/cobbzilla/cobbzilla-utils/blob/master/src/main/java/org/cobbzilla/util/collection/FieldTransformer.java#L28
In the code you posted, it's impossible to create an instance of
T
since you don't know what type that is:Of course it is possible if you have a reference to
Class<T>
andT
has a default constructor, just callnewInstance()
on theClass
object.If you subclass
Abc<T>
you can even work around the type erasure problem and won't have to pass anyClass<T>
references around:You need to get the type information statically. Try this:
Use it as such:
Depending on your needs, you may want to use
Class<? extends T>
instead.It looks like you are trying to create the class that serves as the entry point to your application as a generic, and that won't work... The JVM won't know what type it is supposed to be using when it's instantiated as you start the application.
However, if this were the more general case, then something like would be what you're looking for:
or perhaps:
First of all, you can't access the type parameter
T
in the static main method, only on non-static class members (in this case).Second, you can't instantiate
T
because Java implements generics with Type Erasure. Almost all the generic information is erased at compile time.Basically, you can't do this:
Here's a nice tutorial on generics.
..for example