java - Using parameterized type to determine type -
i going throught link
java generic class - determine type
i tried 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 should printh output 1
prints 2
. please me in understanding this. thanks.
a trick works used in google guice's typeliteral. in constructor of subclass of generic class, do have access parent's generic "instantiation", @ runtime... because generic type information has been retained inheritance purposes @ compile-time. example usage:
typeliteral<myclass> test = new typeliteral<myclass>() {}; // notice {} build anon. subclass system.err.println(test.gettype()); // outputs "myclass"
this not work without using subclass-of-a-generic, due type erasure; , overkill applications.
Comments
Post a Comment