LPD
LPD

Reputation: 2883

Using parameterized type to determine type

I was going throught this link

Java Generic Class - Determine Type

I tried with this program.

package my;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class GenericTypeIdentification {

    public static void main( String args[] ) {
        Node<Integer> obj = new GenericTypeIdentification().new SubNode<Integer>( 1 );
        ParameterizedType parameterizedType = ( ParameterizedType ) obj.getClass().getGenericSuperclass();
        Type clazz = parameterizedType.getActualTypeArguments()[0];
        if ( clazz == Integer.class ) {
            System.out.println( 1 );
        }
        else {
            System.out.println( 2 );
        }
    }

    class Node<T> {

        private final T value;

        public Node( T val ) {
            this.value = val;
        }

        public T evaluate() {
            return value;
        };

    }

    class SubNode<T> extends Node<T> {

        private final T value;

        public SubNode( T val ) {
            super( val );
            value = val;
        }

        @Override
        public T evaluate() {
            return value;
        };
    }
}

My understanding was that it should printh output as 1 but it prints 2. Please help me in understanding this. Thanks.

Upvotes: 2

Views: 426

Answers (2)

tucuxi
tucuxi

Reputation: 17945

A trick that actually works is used in the google guice's TypeLiteral. In the constructor of a subclass of a generic class, you do have access to the parent's generic "instantiation", even at runtime... because the generic type information has been retained for inheritance purposes at compile-time. Example usage:

TypeLiteral<MyClass> test = new TypeLiteral<MyClass>() {}; // notice the {} to build an anon. subclass
System.err.println(test.getType()); // outputs "MyClass"

This does not work without using a subclass-of-a-generic, due to type erasure; and is probably overkill for most applications.

Upvotes: 3

user2742438
user2742438

Reputation:

Clazz would be T in this case.

Generics are considered only at compile time in java. You can attempt to determine the value of the type parameter of a collection at runtime by looking at its members' classes(without 100% certainty, you can end up with a subclass...). There is no way to determine the type parameter value of an empty collection at runtime.

Upvotes: 1

Related Questions