Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generic member initialization

Tags:

java

generics

Suppose I have a Java class parameterized on that contains a private T _member. I want to write a default constructor (no arguments), that somehow initializes my T _member to some known, type T specific value (like -1 for Integer, Float.MAX_VALUE for Float...). Is that possible? I tried new T(), but the compiler doesn't like that. Or do I do nothing, and the default constructor is guaranteed to be called for me?

like image 958
Frank Avatar asked Aug 03 '12 20:08

Frank


People also ask

How do you initialize a generic type in Java?

If you want to initialize Generic object, you need to pass Class<T> object to Java which helps Java to create generic object at runtime by using Java Reflection.

How do you declare a generic variable in Java?

A Generic Version of the Box Class To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.

Can a generic class be instantiated without specifying an actual type argument?

You can create an instance of a generic class without specifying the actual type argument. An object created in this manner is said to be of a raw type. The Object type is used for unspecified types in raw types.


1 Answers

Because of type erasure, at runtime "there is no T".

The way around it is to pass an instance of Class<T> into the constructor, like this:

public class MyClass<T> {

    T _member;

    public MyClass(Class<T> clazz) {
        _member = clazz.newInstance(); // catch or throw exceptions etc
    }

}

BTW, this is a very common code pattern to solve the issue of "doing something with T"

like image 104
Bohemian Avatar answered Oct 12 '22 19:10

Bohemian