Java Generics and Typing from reflection

Is it possible to have a class declared with a generic, and then create an instance of this class by passing the
type of a specific object as the generic parameter ? For example, consider a class defined as

public class SampleGeneric< T > {
      private T _member;
      
      public void setMember( T obj ) {
            _member = obj;
      }
      
      public T getMember() {
            return( _member );
      }
}


Now, normally, I would instantiate this as

SampleGeneric< Integer > sg = new SampleGeneric< Integer >();

but I am interested in instantiating the SampleGeneric class based upon the type of an object....

AnotherType at = new AnotherType();
SampleGeneric< GetType( at ) > sg = new SampleGeneric< GetType( at ) > ();

where GetType( at )  is just my pseudocode for whatever is in the Java Reflection API to do this job.

Can I do this, and if so, how ?

Thanks
jmuldrumAsked:
Who is Participating?
 
Mayank SAssociate Director - Product EngineeringCommented:
0
 
jmuldrumAuthor Commented:
The Sun java tutorial doesn't specifically address my issue. It seems to say that what I need cannot
be done directly because of erasure. I understand that erasure is the reason why I cannot cast using
a generic parameter,  "return(  <T> result ); ", but I am not sure if it eliminates what I am trying to do.
I think that the most important piece of information I am missing is whether or not Java has the ability
to get the type of an object the same way that C# does ( obj.GetType() ).
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.