Instantiating generics type in java - java

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.
}
}

public class Abc<T> {
public T getInstanceOfT(Class<T> aClass) {
return aClass.newInstance();
}
}
You'll have to add exception handling.
You have to pass the actual type at runtime, since it is not part of the byte code after compilation, so there is no way to know it without explicitly providing it.

In the code you posted, it's impossible to create an instance of T since you don't know what type that is:
public class Abc<T>
{
public T getInstanceOfT()
{
// There is no way to create an instance of T here
// since we don't know its type
}
}
Of course it is possible if you have a reference to Class<T> and T has a default constructor, just call newInstance() on the Class object.
If you subclass Abc<T> you can even work around the type erasure problem and won't have to pass any Class<T> references around:
import java.lang.reflect.ParameterizedType;
public class Abc<T>
{
T getInstanceOfT()
{
ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
Class<T> type = (Class<T>) superClass.getActualTypeArguments()[0];
try
{
return type.newInstance();
}
catch (Exception e)
{
// Oops, no default constructor
throw new RuntimeException(e);
}
}
public static void main(String[] args)
{
String instance = new SubClass().getInstanceOfT();
System.out.println(instance.getClass());
}
}
class SubClass
extends Abc<String>
{
}

What you wrote doesn't make any sense, generics in Java are meant to add the functionality of parametric polymorphism to objects.
What does it mean? It means that you want to keep some type variables of your classes undecided, to be able to use your classes with many different types.
But your type variable T is an attribute that is resolved at run-time, the Java compiler will compile your class proving type safety without trying to know what kind of object is T so it's impossible for it to let your use a type variable in a static method. The type is associated to a run-time instance of the object while public void static main(..) is associated to the class definition and at that scope T doesn't mean anything.
If you want to use a type variable inside a static method you have to declare the method as generic (this because, as explained type variables of a template class are related to its run-time instance), not the class:
class SandBox
{
public static <T> void myMethod()
{
T foobar;
}
}
this works, but of course not with main method since there's no way to call it in a generic way.
EDIT: The problem is that because of type erasure just one generic class is compiled and passed to JVM. Type checker just checks if code is safe, then since it proved it every kind of generic information is discarded.
To instantiate T you need to know the type of T, but it can be many types at the same time, so one solution with requires just the minimum amount of reflection is to use Class<T> to instantiate new objects:
public class SandBox<T>
{
Class<T> reference;
SandBox(Class<T> classRef)
{
reference = classRef;
}
public T getNewInstance()
{
try
{
return reference.newInstance();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static void main(String[] args)
{
SandBox<String> t = new SandBox<String>(String.class);
System.out.println(t.getNewInstance().getClass().getName());
}
}
Of course this implies that the type you want to instantiate:
is not a primitive type
it has a default constructor
To operate with different kind of constructors you have to dig deeper into reflection.

You need to get the type information statically. Try this:
public class Abc<T> {
private Class<T> clazz;
public Abc(Class<T> clazz) {
this.clazz = clazz;
}
public T getInstanceOfT()
throws throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException,
NoSuchMethodException,
SecurityException {
return clazz.getDeclaredConstructor().newInstance();
}
}
Use it as such:
Abc<String> abc = new Abc<String>(String.class);
abc.getInstanceOfT();
Depending on your needs, you may want to use Class<? extends T> instead.

The only way to get it to work is to use Reified Generics. And this is not supported in Java (yet? it was planned for Java 7, but has been postponed). In C# for example it is supported assuming that T has a default constructor. You can even get the runtime type by typeof(T) and get the constructors by Type.GetConstructor(). I don't do C# so the syntax may be invalid, but it roughly look like this:
public class Foo<T> where T:new() {
public void foo() {
T t = new T();
}
}
The best "workaround" for this in Java is to pass a Class<T> as method argument instead as several answers already pointed out.

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:
T member = new T();
Here's a nice tutorial on generics.

You don't seem to understand how Generics work.
You may want to look at http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html
Basically what you could do is something like
public class Abc<T>
{
T someGenericThing;
public Abc(){}
public T getSomeGenericThing()
{
return someGenericThing;
}
public static void main(String[] args)
{
// create an instance of "Abc of String"
Abc<String> stringAbc = new Abc<String>();
String test = stringAbc.getSomeGenericThing();
}
}

I was implementing the same using the following approach.
public class Abc<T>
{
T myvar;
public T getInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException
{
return clazz.newInstance();
}
}
I was trying to find a better way to achieve the same.
Isn't it possible?

Type Erasure Workaround
Inspired by #martin's answer, I wrote a helper class that allows me to workaround the type erasure problem. Using this class (and a little ugly trick) I'm able to create a new instance out of a template type:
public abstract class C_TestClass<T > {
T createTemplateInstance() {
return C_GenericsHelper.createTemplateInstance( this, 0 );
}
public static void main( String[] args ) {
ArrayList<String > list =
new C_TestClass<ArrayList<String > >(){}.createTemplateInstance();
}
}
The ugly trick here is to make the class abstract so the user of the class is forced to subtype it. Here I'm subclassing it by appending {} after the call to the constructor. This defines a new anonymous class and creates an instance of it.
Once the generic class is subtyped with concrete template types, I'm able to retrieve the template types.
public class C_GenericsHelper {
/**
* #param object instance of a class that is a subclass of a generic class
* #param index index of the generic type that should be instantiated
* #return new instance of T (created by calling the default constructor)
* #throws RuntimeException if T has no accessible default constructor
*/
#SuppressWarnings( "unchecked" )
public static <T> T createTemplateInstance( Object object, int index ) {
ParameterizedType superClass =
(ParameterizedType )object.getClass().getGenericSuperclass();
Type type = superClass.getActualTypeArguments()[ index ];
Class<T > instanceType;
if( type instanceof ParameterizedType ) {
instanceType = (Class<T > )( (ParameterizedType )type ).getRawType();
}
else {
instanceType = (Class<T > )type;
}
try {
return instanceType.newInstance();
}
catch( Exception e ) {
throw new RuntimeException( e );
}
}
}

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 a String[] 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 type E[] 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.
public <E> E[] array (Collection c) {
if (c == null) return null;
if (c.isEmpty()) return (E[]) EMPTY_OBJECT_ARRAY;
final List<E> collect = (List<E>) CollectionUtils.collect(c, this);
final Class<E> elementType = (Class<E>) ReflectionUtil.getterType(c.iterator().next(), field);
return collect.toArray((E[]) Array.newInstance(elementType, collect.size()));
}
Full code is here: https://github.com/cobbzilla/cobbzilla-utils/blob/master/src/main/java/org/cobbzilla/util/collection/FieldTransformer.java#L28

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:
public MyGeneric<MyChoiceOfType> getMeAGenericObject(){
return new MyGeneric<MyChoiceOfType>();
}
or perhaps:
MyGeneric<String> objMyObject = new MyGeneric<String>();

Abc<String> abcInstance = new Abc<String> ();
..for example

Related

Generic wildcards in return types - how to avoid?

Sonar says
Generic wildcard types should not be used in return types
Now I have to use an API that accepts an Iterable<SomeType<?>> as parameter. How should I create this parameter without violating the Sonar rule if I want to create it in a separate method - so not inline like List<SomeType<?>> param = new ArrayList();
Some code I've played around with:
interface X<T> {
}
static class Blarp {
void addSomeBlarps(Iterable<X<?>> blub) {
}
}
#Test
void testGenerics() {
Blarp b = new Blarp();
X<?> c = new X<>() {};
X d = new X() {};
List<X> blarpList = new ArrayList();
blarpList.add(c);
blarpList.add(d);
List<X<?>> blubList = new ArrayList<>();
blubList.add(c);
blubList.add(d);
// blubList.addAll(blarpList); does not work - why? why can a single X be added but not multiple?
// blubList.addAll((Collection<? extends X<?>>) blarpList); does seem to work with IntelliJ but then fails on compile
// b.addSomeBlarps(blarpList); doesn't work - why?
b.addSomeBlarps(blubList);
}
Probably there's a misunderstanding.
Let's have a look at
public void someMethod(SomeType<?> param) { ... }
This method accepts a parameter param which has to be of the parameterized type SomeType but the method doesn't mind the type parameter (put casually). That is, you can call this method with any parameter of type SomeType regardless of the used type parameter.
So, you can create your objects with a concrete type parameter and hand it over to the method, for example
public class Test<T> {
public static void main(String[] args) {
print(newTestString());
print(newTestLong());
}
public static void print(Test<?> someTest) {
System.out.println(someTest);
}
public static Test<String> newTestString() {
return new Test<String>();
}
public static Test<Long> newTestLong() {
return new Test<Long>();
}
}
Update
The misunderstanding was at my side as it's about a generic type of a generic type. That's a different story. In the example the type is an Iterable which is parameterized by SomeType<?>. The problem is, that Iterable<SomeType<String>> is not a subtype of Iterable<SomeType<?>>.
The method would have to accept e. g. a parameter of type Iterable<? extends SomeType<?>> to be able to pass a Iterable<SomeType<String>>.
As the method is given the way it is, you'll have to work around.
(EDIT: deleted crap I wrote)
I would either not factor out the creation of the object or suppress the warning in that case.

Java generics - Does Java need support for locally defined types?

I am hoping to reach the Java generics experts here. Let's say you have some typed class:
public interface SomeClass<T> {
void doSomething(final T t);
}
There is also a function which gets you an instance of T given an instance of SomeClass<T>:
public static class Retriever {
public <T> T get(final SomeClass<T> c) {
return null; // actual implementation left out
}
}
Now let's say you have a collection of SomeClass<?> and a retriever:
final List<SomeClass<?>> myClasses = null; // actual implementation left out
final Retriever myRetriever = null; // actual implementation left out
We are not able to do the following:
for (final SomeClass<?> myClass : myClasses) {
myClass.doSomething(myRetriever.get(myClass));
}
Now my question: does Java need support to be able to locally define a type? Something like:
<T> for (final SomeClass<T> myClass : myClasses) {
myClass.doSomething(myRetriever.get(myClass));
}
Here, the type T is scoped to the for-loop. We are defining T to get rid of the wildcard ?. That's it. The introduction of T should enable us to write the desired for loop as expressed above.
FWIW, the following code is a workaround. We are introducing a function, solely for the conversion of ? to T.
for (final SomeClass<?> myClass : myClasses) {
workAround(myRetriever, myClass);
}
public static <T> void workAround(final Retriever myRetriever, final SomeClass<T> myClass) {
myClass.doSomething(myRetriever.get(myClass));
}
A locally defined user type might be a more elegant solution?
Now my question: does Java need support to be able to locally define a type?
No. The minimal scope of a type-parameter is the method, i.e. in order to have the type T available for your for loop, you will have to either defined the enclosing method a generic or the enclosing class. For example:
<T> void method(List<SomeClass<T> myClasses) {
for (final SomeClass<T> myClass : myClasses) {
myClass.doSomething(myRetriever.get(myClass));
}
}

How to get Class<?> object of a generic type

I have a static method which will return a custom type based on the type of the class,
public class GenericMethod {
public static <T> T returnGeneric(Class<T> clazz) {
return null;
}
}
Now, I want to pass a class with a generic type in to it,
CustomType<String> type = GenericMethod.returnGeneric(CustomType.class);
Only problem is that the above statement gives and unchecked conversion warning.
I tried the workaround new CustomType<String>().getName() which is also not solving the problem.
Is there a right way to it, or the only solution is to use #SuppressWarnings ?
What you would/should like to try is this:
CustomType<String> type = GenericMethod.returnGeneric(CustomType<String>.class);
Unfortunately, because of type erasure there is no difference between CustomType<A>.class and CustomType<B>.class, hence this syntax is not supported by Java.
So my $.02: what you are asking for is not possible, so hang on to the #suppresswarnings...
The best approach is to use a wrapper method and place all your warnings in a single place.
And the term "unchecked" means that the compiler does not have enough type information to perform all type checks necessary to ensure type safety.
In theory you can't do it because of type erasure.
In practice though ;) you can do it because the information is actually in the .class files.
The easiest way I know of is using Spring's GenericTypeResolver.
Have a look at it.
As you said #Simeon "In theory you can't do it because of type erasure".
You can use it only if you have subclasses of CustomType:
class GenericMethod {
public static <T> T returnGeneric(Class<T> clazz) {
try {
return clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public static void main(String [] args){
CustomeType<String> ct = returnGeneric(StringCustomeType.class);
System.out.println(ct);
}
}
class StringCustomeType extends CustomeType<String> {
}
class CustomeType<T> {
}

Is there an easier way to retrieve hard-coded type parameters in subclass implementations?

Given the following interface:
public interface GenericInterface<T> {
T getValue();
void setValue(T newVal);
}
And the following impl:
public class FixedImpl implements GenericInterface<String> {
String value;
public FixedImpl(String value) {
this.value = value;
}
#Override
public String getValue() {
return value;
}
#Override
public void setValue(String newVal) {
value = newVal;
}
}
I want to be able to determine that in the case of FixedImpl, String.class is the value for GenericInterface.T by interrogating FixedImpl.class.
My current idea:
Find a method name in GenericInterface that returns a <T> - in this case, there's "getValue".
Go through all the methods declared in FixedImpl.class with the same name, and collect all the different return types.
The return type farthest from Object is my value for GenericInterface.T.
But there's a couple of issues with this process:
It will only work for generic types containing a method that returns <T>. You can't safely do the same trick using setValue(T), because method overloading by parameter / arity is possible to do in Java source. It only works for T getValue() because overloading by return value isn't (unless I'm mistaken).
It might have weird interactions with Java 8 default methods, or a generic method implementation in a (still generic) possibly abstract superclass.
It's kinda kludgey.
Can anybody point me to an easier / more surefire way to get the same information? I can't seem to find one, but I thought I'd ask the superior intellects of the toobs :)
NB: If you're wondering why I'd need this, it's because I want to programatically construct mocks of container classes with similar hard-coded type parameters, but POJO values rather than simple Strings.
EDIT: I eventually worked out the following solution (before seeing #stony-zhang's):
public static <G> List<Class> getConcreteTypes(Class<? extends G> implClass, Class<G> genericClass) {
List<Class> concreteTypes = new ArrayList<Class>();
for (Type type : implClass.getGenericInterfaces()) {
if (!(type instanceof ParameterizedTypeImpl)) continue;
ParameterizedTypeImpl parameterizedType = (ParameterizedTypeImpl) type;
if (parameterizedType.getRawType() != genericClass) continue;
for (Object arg : parameterizedType.getActualTypeArguments()) {
if (!(arg instanceof Class))
throw new IllegalArgumentException("Class " + implClass + " not concrete for generic type " + genericClass);
concreteTypes.add((Class) arg);
}
}
return concreteTypes;
}
You can get the the class of T by the following way, in the interface add a method getMessageClass(), and in the FixedImpl add the implemented method,
#SuppressWarnings("rawtypes")
public Class getMessageClass() {
int index =0; //In the case, you only have a generic type, so index is 0 to get the first one.
Type genType = getClass().getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
throw new RuntimeException("Index outof bounds");
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}
In you case, if you have multiple subclass, to use it, create one abstract class to implement the interface GenericInterface, and then the all subclass extends from the new abstract class,
public class abstract abstractImpl<T> implements implements GenericInterface<T> {
#SuppressWarnings("rawtypes")
#Override
public Class getMessageClass() {
...............
}
}
Remember type erasure. At runtime, there is no type information about your generics anymore, unless you specify it yourself. And this is what you should do. Add this to your interface:
Class<T> getTypeOfT();
And add this to your FixedImpl:
#Override
public Class<String> getTypeOfT()
{
return String.class;
}
That way, you can always call getTypeOfT() on your GenericInterface<T> implementations and find out what type you are dealing with.
I don't think that you will be able to get reliable result because of Type Erasure:
Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
Insert type casts if necessary to preserve type safety.
Generate bridge methods to preserve polymorphism in extended generic types.
Your approach of of using the types of objects returned may at first seem alright, but beyond the issues you have pointed out there is no way (at runtime) to know if The return type farthest from Object is my value for GenericInterface.T.
My suggestion would be to use some kind of configuration XML which could be generated at build time based on the java source (using a build tool such as Ant), which would in turn be used to create Mock objects, or you could simply generate the tests based off the source at buildtime.
If you don't mind changing your runtime code for the purposes of testing, Jan Doereenhaus' answer suggests a simple hard-coded mechanism for retrieving the type
EDIT:
Consider the scenario:
public class FixedImpl implements GenericInterface<SomeClass> {
#Override
public SomeClass getValue() {
return new SomeClass();
}
}
public class FixedImpl2 extends FixedImpl {
#Override
public SomeClass getValue()
{
return new SomeSubClass();
}
}
From this example, you can see that the sub class of FixedImpl is able to return a subclass of T (which is further down the inheritance hierarchy from Object)

Java Generics limitations or wrong usage?

I have a class representing a pair of two values of the same type (type which can be any of a specific set of types ):
public class Pair<E extends AClass>{
private E var1;
private E var2;
}
This class is used by a framework, so it needs a no-argument constructor in which I have to instantiate the 2 variables (var1, var2):
public class Pair<E extends AClass>{
private E var1;
private E var2;
public Pair(){
var1 = invoke constructor of type E;
var2 = invoke constructor of type E
}
}
There are obviously a number of problems here:
In order to instantiate the variables I should somehow know its exact type and invoke that specific type's constructor; in the best case this means to have a pretty large if else statement in the constructor, something like:
public Pair(){
if(var1 instanceof SpecificType1){
var1 = new SpecificType1();
var2 = new SpecificType2();
}
}
Even if I do as above, I will have some problems because var1 is declared of type E and I will get a type mismatch error when trying to instantiate SpecficType1 and to assign the resulted object to var1/var2. In order to make it work, I have to cast to E :
var1 = (E)new SpecificType1();
But this destroys the compile time type checking as I'm trying to cast a specific type to a generic type.
Is this a limitation of the Generics in java or is this scenario a bad one for using Generics ?
In order to instantiate the variables I should somehow know its exact type and invoke that specific type's constructor; in the best case this means to have a pretty large if else statement in the constructor, something like:
You'll run into problems before that.
if(var1 instanceof SpecificType1){
var1 = new SpecificType1();
var2 = new SpecificType2();
}
var1 is null at this point, so var1 instanceof T is false for all T.
One limitation of Java generics is that generic type parameters are erased so there's no way that you can reflect on the type parameter from a zero-argument constructor.
The caller has to provide some context to tell you how to initialize var1 and var2, and the typical way to provide that context is via constructor arguments.
Your best option is probably to let var1 and var2 start off null and then delay initialization until such time as you can get the context you need.
Perhaps
void init(Class<E> type) {
if (type.isAssignableFrom(ConcreteType1.class)) {
var1 = type.cast(new ConcreteType1(...));
var2 = type.cast(new ConcreteType1(...));
} else { /* other branches */ }
}
This isn't perfect since you still can't distinguish E extends List<String> from E extends List<Number> but it may be good enough for your case, and the .cast method will give you a type-safe cast to E.
Alternatively, Guava, Guice, and related libraries provide things like the Supplier<E> interface which may come in handy in an init method.
You cannot instantiate a generic type - What will happen if for example the generic type is SomeAbstractClass? What will be instantiated? (this is not the reason, it is just intuition)
However, you can use java reflection API to instantiate the object - but you will need the specific class object for it.
A more elegant alternative is using the abstract factory design pattern, and pass a factory object to your pair, and use it to construct the needed object.
Code sample:
public class Pair<S> {
public final S var1;
public final S var2;
public Pair(Factory<S> builder) {
var1 = builder.build();
var2 = builder.build();
}
}
public interface Factory<S> {
public S build();
}
public class IntegerBuilder implements Factory<Integer> {
private int element = 5;
public Integer build() {
return new Integer(element++);
}
}
If a framework were to instantiate it, it would do it as a raw type, something equivalent to new Pair() with no type parameters.
I guess you have to create simple one-liner classes like:
class SpecificType1Pair extends Pair<SpecificType1> {}
and pass them to the framework instead. You can get the actual type parameter as getClass().getGenericSuperclass()).getActualTypeArguments()[0]. You class pair would look like this:
public abstract class Pair<E extends AClass> {
private E var1;
private E var2;
public Pair() {
ParameterizedType superclass = (ParameterizedType) getClass().getGenericSuperclass();
#SuppressWarnings("unchecked")
Class<E> clazz = (Class<E>) superclass.getActualTypeArguments()[0];
try {
var1 = clazz.newInstance();
var2 = clazz.newInstance();
} catch (InstantiationException e) {
handle(e);
} catch (IllegalAccessException e) {
handle(e);
}
}
}

Categories