Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic class - getClass().getName()

Tags:

java

generics

I have a generic base class:

public class BaseLabel<T> extends JXLabel {
    private static final long serialVersionUID = 1L;

    public BaseLabel() {
        System.out.println(T.class.getClass().getName()); //error
    }       
}

and Child class:

public class ChildLabel extends BaseLabel<ChildLabel> {
    private static final long serialVersionUID = 2L;

    public ChildLabel() {

    }       
}

I am getting compilation error.

Is there any way to get the actual class name from the constructor of BaseClass. Here, by actual class I am referring to that class, which I am going to instantiate.

For example I am instantiating ChildClass, ChildClass clz = new ChildClass();

then that println() will print package.ChildClass.

Thanks in advance.


The compilation error is:

cannot select from a type variable System.out.println(T.class.getClass().getSimpleName());

If I call this.getClass.getSimpleName() from the abstract BaseClass's constructor. It is printing the ChildClass.

Why?

Is it due to, as I am instantiating ChildClass so this is pointing to the ChildClass's object.

like image 568
Tapas Bose Avatar asked Dec 05 '25 02:12

Tapas Bose


2 Answers

Ugly? yes

import java.lang.reflect.ParameterizedType;


public class GenericClass<T> {

    public GenericClass() {
        System.out.println(getClass().getGenericSuperclass()); //output: GenericClass<Foo>
        System.out.println(((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]); //output: class Foo
    }

    public static void main(String[] args) {
        new ChildClass();
    }

}

child class

import java.lang.reflect.ParameterizedType;


public class ChildClass extends GenericClass<Foo> {

    public ChildClass() {
        System.out.println(((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]); //output: class Foo
    }

}
like image 131
Vincent Vanmarsenille Avatar answered Dec 07 '25 18:12

Vincent Vanmarsenille


It's not possible to find this information from your class BaseLabel at run time as it doesn't 'know' what type it's generic has been instantiated with. This is because Java uses type erasure for generics - generic parameters aren't runtime artefacts.

like image 39
matthewSpleep Avatar answered Dec 07 '25 18:12

matthewSpleep