Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Generics via reflection and newInstance()

800351Jul 23 2005 — edited May 27 2007
I'm looking for a way, or a correct syntax, for 'genericizing' the
class instantiation via Class#newInstance() method using reflection.
The code shown below is an half-baked solution in that compiler emits
unchecked cast warning against the cast on the 'obj' variable at the
last part of the code.

I think I have tried everyting conceivable for Class variable declarations
and other part of the code but they were all futile. I lost one night
sleep for that.

If there are Java Generics gurus on the forum, please help!

TIA.
import java.util.*;
import java.lang.reflect.*;

public class GetMethod{
  public static void main(String[] args) {
    Object obj = null;
    Class<Hashtable> clazz = Hashtable.class;
    Class<Class> claxx = Class.class;
    try {
      Method method = claxx.getMethod("newInstance");
      obj = method.invoke(clazz);
    } 
    catch (Exception e) {
      e.printStackTrace();
    }
    Hashtable<String,String> ht = (Hashtable<String,String>)obj;
    ht.put("foo", "bar");
    System.out.println(ht.get("foo"));
  }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 24 2007
Added on Jul 23 2005
11 comments
206 views