Java element initialization

Suppose I have a Java class parameterized on it containing a private T_member. I want to write a default constructor (without arguments) that somehow initializes my T_member with some well-known type-specific value (for example, for Integer, Float.MAX_VALUE for Float ...). Is it possible? I tried the new T (), but the compiler doesn't like this. Or am I doing nothing, and is the default constructor guaranteed to be called for me?

+6
source share
4 answers

Each field in Java without an initializer expression is automatically initialized with a known default value. And yes, in this case, this known value of type T is null .

+3
source

Due to the type of erasure , the runtime is "T no."

The path to it is to pass an instance of Class<T> to the constructor, for example:

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

By the way, this is a very common code template for solving the "do something with T" problem

+5
source

This is not possible because there is no way to guarantee that T has a default constructor. However, you could do this using reflection using newInstance . Just be sure to catch any exceptions that may be thrown.

 public class MyClass<T> { private T _member; public MyClass(Class<T> cls) { try { _member = cls.newInstance(); } catch (InstantiationException e) { // There is no valid no-args constructor. } } } 
+3
source

In fact there is a way to do this, here is a link to the answer to the corresponding SO question.

So, actually your main question is, if there is an opportunity to get a class of a generic member at runtime? Yes, there is - the use of reflection.

When I came up with this answer about a year ago, I tested it and researched a bit. In fact, there were several cases when it did not work as it is (to be an imposition of cases with inheritance), but on the whole it is a mistake to say that this is impossible.

However, I strongly suggest not doing it this way.

EDIT. Surprisingly, I found my own comment below this answer :) And in the next comment there is a link of the author to the original article on the reflection of generics.

0
source

Source: https://habr.com/ru/post/922081/


All Articles