How To: Use reflection to create instance of generic type?

I would like to be able to use reflection to instantiate an instance of a generic type, but can't seem to avoid getting type safety warnings from the compiler. (I'm using Eclipse 3.1.1) Here is a trivial example: suppose I want to create an instance of a list of strings using reflection.
My first guess was to write the following:
Class cls = Class.forName("java.util.ArrayList<String>");
List<String> myList = cls.newInstance();The call to Class.forName throws a ClassNotFoundException. OK, fine, so I tried this:
Class cls = Class.forName("java.util.ArrayList");
List<String> myList = cls.newInstance();Now the second line generates the warning "Type safety: The expression of type List needs unchecked conversion to conform to List<String>".
If I change the second line to
List<String> myList = (List<String>)cls.newInstance();then I get the compiler warning "Type safety: The cast from Object to List<String> is actually checking against the erased type List".
This is a trivial example that illustrates my problem. What I am trying to do is to persist type-safe lists to an XML file, and then read them back in from XML into type-safe lists. When reading them back in, I don't know the type of the elements in the list until run time, so I need to use reflection to create an instance of a type-safe list.
Is this erasure business prohibiting me from doing this? Or does the reflection API provide a way for me to specify at run time the type of the elements in the list? If so, I don't see it. Is my only recourse to simply ignore the type safety warnings?

Harald,
I appreciate all your help on this topic. I think we are close to putting this thing to rest, but I'd like to run one more thing by you.
I tried something similar to your suggestion:public static <T> List<T> loadFromStorage(Class<T> clazz) {
    List<T> list = new ArrayList<T>();
    for ( ...whatever ...) {
       T obj = clazz.newInstance();
       // code to load from storage ...
       list.add(obj);
    return list;
}And everything is fine except for one small gotcha. The argument to this method is a Class<T>, and what I read from my XML storage is the fully qualified name of my class(es). As you pointed out earlier, the Class.forName("Foo") method will return a Class<?> rather than a Class<Foo>. Therefore, I am still getting a compiler warning when attempting to produce the argument to pass to the loadFromStorage method.
I was able to get around this problem and eliminate the compiler warning, but I'm not sure I like the way I did it. All of my persistent classes extend a common base class. So, I added a static Map to my base class:class Base
   private static Map<String, Class<? extends Base>> classMap = null;
   static
      Map<String, Class<? extends Base>> map = new TreeMap<String, Class<? extends Base>>();
      classMap = Collections.synchronizedMap(map);
   public static Class<? extends Base> getClass(String name)
      return classMap.get(name);
   protected static void putClass(Class<? extends Base> cls)
      classMap.put(cls.getName(), cls);
}And added a static initializer to each of my persistent classes:class Foo extends Base
   static
      Base.putClass(Foo.class);
}So now my persistence code can replace Class.forName("my.package.Foo") with Base.getClass("my.package.Foo"). Since Foo.class is of type Class<Foo>, this will give me the Class<Foo> I want instead of a Class<?>.
Basically, it works and I have no compiler warnings, but it is unfortunate that I had to come up with my own mechanism to obtain a Class<Foo> object when my starting point was the string "my.package.Foo". I think that the JDK, in order to fully support reflection with generic types, should provide a standard API for doing this. I should not have to invent my own.
Maybe it is there and I'm just not seeing it. Do you know of another way, using reflection, to get from a string "my.package.Foo" to a Class<Foo> object?
Thanks again for your help,
Gary

Similar Messages

  • Creating instance of generic type

    Hi.
    Here is my class
    public class ManagerForm<M extends Stuff>{
    private Class<M>clazz;
    private M manager;
    public void setWorker(M manager){
    this.manager=manager;
    public M getWorker(){
    return this.manager;
    private final Class<M> getGenericClass() {
    Class<M> persistentClass = null;
    Type genericType = getClass().getGenericSuperclass();
    if (genericType instanceof ParameterizedType) {
    ParameterizedType pType = ((ParameterizedType) genericType);
    // obtaining first generic type class
    persistentClass = (Class<M>) pType.getActualTypeArguments()[0];
    return persistentClass;
    public ManagerForm(){
    this.clazz=getGenericClass();
    this.manager=this.clazz.newInstance();
    In default constructor I need to inicialize U instance this.user.
    I have an nullPointerException in line this.manager=this.clazz.newInstance();
    persistantClass is returned nullable because genericType is not instance of ParameterizedType.
    Could anybody say me what is wrong or propose other methods to create generic instance. I need help. Will be very appreciable.
    Thanks in advance.

    YoungWinston wrote:
    877715 wrote:
    Could anybody say me what is wrong or propose other methods to create generic instance. I need help. Will be very appreciable. I think you need to back up and explain exactly what you're trying to do here.
    It would appear that you're attempting to divine the actual type of a specific ManagerForm, but I'm not absolutely certain. Also, since you already specify the type as a field, why can't you just usemanager.getClass()? I suspect that all you'll get from getClass().getGenericSuperclass() is 'Stuff', but I have to admit I'm no expert on this.
    Far better to describe what you want than an implementation that plainly doesn't work.
    WinstonWell. I have class ManagerForm<M extends Stuff>. there is private field manager that have generic type M. And I need to instantinate manager in default constructor.
    I cant write
    public ManagerForm(){
    this.manager=new M();//will be compiler error
    Thats why exists a mechanism to get current generic type in runtyme through ParameterType.
    I have method getGenericClass that gets current class in runtime and then I create an instance of this class through <class>.newInstance(); And this is the standard way to instantinate generic type.
    I hoped line Type genericType = getClass().getGenericSuperclass(); of method returned ParameterizedType. But variable genericType cannot be casted to ParameterizedType. I don't know why. So I cannot get current generic param M and instantiate its.

  • How to use SNRO to create daily number range?

    Dear all,
    I would like to know how to use SNRO to create a daily number range.
    We would like to have the following sequence. The first 8 digits are date and the last 2 digits are number sequence. Each day, the last 2 digits will start from 01 again. i.e. <8-digits date><2-digit sequence>
    For example, today is 22 May 2006,
    2006052201
    2006052202
    2006052203
    Tomorrow will have sequence like this:
    2006052301
    2006052302
    2006052303
    Thanks!

    Thomas,
    I don't there is a automated way of doing as the dates do NOT follow a numbering sequence. What you can do is to create a number range for getting the last two digits every day and manually concatenate the date with the serial number.
    However, as you have to reset the counter every day that might be a issue.
    Regards,
    Ravi

  • I was wondering how to use Dreamweaver to create joomla template? Any ideas or useful resources.

    I am embarking on a new project to create a joomla template. I need your ideas on how to use Dreamweaver to create the template. TQ

    It's pretty much the same procedure with all your open source CMSs (WordPress, Drupal, Joomla!...)
    Start with this 4 Part Tutorial:
    http://www.adobe.com/devnet/dreamweaver/articles/dw_wordpress_pt1.html
    Nancy O.
    Alt-Web Design & Publishing
    Web | Graphics | Print | Media  Specialists 
    http://alt-web.com/
    http://twitter.com/altweb

  • How to use CSS to create horizontal nav bar in Dreamweaver CS6

    How to use CSS to create horizontal nav bar in Dreamweaver CS6

    One of the ways to do it is this: Tryit Editor v1.9
    You can also use floats to get something to the same effect.

  • How to use the dll  created by c++ but not write a jni wrapper around

    how to use the dll created by c++ but not write a jni wrapper around through a java program. now I can't access that dll like this directly from java.

    Your question is unclear. (You haven't said what dll you are talking about.)
    But:
    If you are talking about an existing dll, then the only alternative to writing a wrapper is to use one of the wrapper generators floating around. Do a search on JACE.
    If you are talking about a dll you are writing, then run jah and get the interface to match java right away; then you won't have to write a wrapper.

  • How to use reflection to get base classes protected field

    I have one base Base classes which have protected fields and public get method to get the field.
    class Base
    protected int proField;
    public int getProField(){return proField;}
    Class Derive extends base class Base
    class Derive extends Base implements OtherInterface
    public void funtion(){};
    Now I have an instance of Derive, how can I use reflection to get the protected field inherited from Base. It seems Java Reflection only give runtime accessibility to public field and decleared field, protected-inherited field is excluded.
    Thanks
    Lei

    as the last poster said, traverse up the class hierarchy.
    ex:
    private void doSumfinToField(String fieldName throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException {
    Class clazz = getClass();
    Field field = findFieldInClass(clazz, fieldName);
    //field.doSumfin;
    private Field findFieldInClass(Class clazz, String fieldName) throws NoSuchFieldException {
    try { // to find the field in this class    
    return clazz.getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
    // if we don't have a superclass, continue
    if (clazz.getSuperclass().equals(Object.class)) {
    throw e;
    // check in the superclass
    return findFieldInClass(clazz.getSuperclass(), fieldName);
    }

  • Anoyone know how to use Reflection?

    I'd like to export certain properties from an ai-document to XML. The XML will be post-processed using XSLT. Secretly, I'm hoping that I can invoke the Reflection-system (as mentioned brifely, I might add) in the ExtendedScript Toolkit CS6 Core JavaScript Classes.
    Do anyone know how to get reflection working for JavaScript objects (both built-in and the ones I've created in code my self)? Are there any guides that are relevant in my case? (Try googling "illustrator script reflection" and you get a bunch of flip object scripts ...)

    Found it. Had to alter my google query ... (Try "extendscript reflection", and you'll see what I mean.)
    For reference, try the following:
    var xmlSource = myCustomObject.reflect.toXML();
    alert ( xmlSource );

  • How to use a session, created in a jsp page, in a php page

    Hello, forgive me for the newbie question.
    Here is my problem:
    I want to have a jsp page create a session, set some session variables and then redirect to a php page which will access those same session variables.
    I have the redirection worked out, but I can't seem to find out how to use the jsp session in my php script.
    Is this possible at all, and if so, how does it work?

    Note that javascript runs on the client side, and JSP runs on the server. JSP and the session objects are NOT available to javascript in reaction to the user.
    If this function is called only when the page is first created, not when the user interacts with the page, or if you want that value to be constant with respect to the javascript, then you can do this:
    <%
      String someValue = (String)session.getAttribute("theAttributeName");
    %>
    <script type="text/javascript">
         Calendar.setup({inputField:"f_date_dfFirstPmtDate",
                                              button:"f_trigger_dfFirstPmtDate",
                                             singleClick:true,
                                              ifFormat:<%=someVale%>});
    </script>

  • Using PAPI to create instance on Enterpise

    Hi.
    I have deployed my process on Enterprise edition with weblogic and oracle.
    I need to know all the libraries required for writing PAPI program to create instance.
    Also anything i should take care of while writing the java program to create instance using PAPI.
    Like. do i need to have weblogic.jar in the classpath. or any other jars.
    Regards
    Right Chord

    Thanks,
    Maybe I didn't explain exactly what I was expecting with the standby database, these steps are what I did, to resolve the issue
    ENABLE THE STANDBY DATABASE TO STARTUP FROM SPFILE
    Step 1: create a newly spfile from the current pfile
    SQL> CREATE SPFILE='C:\ORACLE\PRODUCT\10.2.0\DB_1\DATABASE\SPFILEORCL.ORA' FROM PFILE='C:\ORACLE\PRODUCT\10.2.0\DB_1\DATABASE\INITORCL.ORA';
    Step 2: Rename the INITORCL.ORA TO SAVE_DATE_INITORCL.ORA
    Example: the C:\ORACLE\PRODUCT\10.2.0\DB_1\DATABASE\INITORCL.ORA became
    C:\ORACLE\PRODUCT\10.2.0\DB_1\DATABASE\SAVE_24072007_INITORCL.ORA
    Step 3: delete the former sid created
    C:\ORADIM -delete -sid orcl
    Instance deleted.
    Step 3: Change the Oracle service to start when the OS start
    C:\ ORADIM -new -sid ORCL -SRVC OracleServiceORCL -STARTMODE auto -SRVCSTART system -SPFILE
    Instance created.
    Now When I shutdown the whole system and start it up, the standby database startup. the only thing is that the standby database startup a read-only mode, defautl with oracle 10g this is fine for me, because the MRP is stopped but the log shipping is not stopped.
    So eventhough the system admin shutdown the database server at OS level without letting me know, tha standby should continue receiving archived log files.
    I'll just need to monitore the lop apply process and start it to apply archived log files received
    Thanks

  • How to Use iSetup to create new environment in copy of clean master.

    Hi,
    I want to use iSetup to create a complete new environment. No manual setup has been done yet in the copy of the master (no Business Group, No OU, no Chart of Acc: nothing). Source environment is being setup rightnow by functional consultants
    Can one please provide me with a manual or guideline how to start this challenging job. Maybe a best practise can be used ?
    In the end we want to setup an environment based on a clean master.
    ( practical data: eBS 12.1.2 on linux )
    Thanks in advance
    Guido

    Hi Guido,
    You can get in touch with [email protected] who is the product manager for iSetup. He would able to assist you to go forward in the right direction.

  • How to use BAPI_PROJECT_MAINTAIN to create network activities under WBS elements ?

    Hello ABAPers,
    I have been using BAPI_PROJECT_MAINTAIN to create Project and WBS elements and I have done them without any errors.
    Now I need help on how to create network activities.
    Can anyone share on how to pass data to I_NETWORK table and I_ACTIVITY table and a brief description on what they are ?
    Thanks in advance,
    Kiran

    Hi Kiran,
    Do the following steps
    1.pass the following to i_method_project
    method_project-refnumber = lv_refnum.
    method_project-objecttype = 'NETWORK-ACTIVITY'.
    method_project-method = 'UPDATE'.
    concatenate aufnr(network nr) vornr(activity) into method_project-objectkey.
    2.Into i_activity
    activity-network = aufnr.
    activity-activity = vornr.
    3.i_activity_update
    activity_update-network = 'X'.
    activity_update-activity = 'X'.
    It should work.If not let me know.
    Rgds,
    K.S.

  • How to use cdrw to create multi-session cd?

    I use cdrw to create multi-session cd as this:
    # cdrw -O -i /tmp/1.iso
    contents in 1.iso can be read by both Solaris and Windows, then
    # cdrw -O -i /tmp/2.iso
    Solaris consider the cd is empty and Windows consider the cd is not existed.
    My question is, how to handle multi-session cd in Solaris? From some cdrecord FAQ, the data was there but TOC was broken, so one tip is importing TOC of previous sessions before burn. But how?

    Honestly I know this is sort of a weak point with Macs. Not really sure why. I guess with the price of HD storage getting cheaper as well as writable media it's just not something people are interested in enough. But that's too bad because it does seem to have interest.
    Anyway you might check out Burn Again

  • How to use LT03 to create TO by WBS delivery

    Hi,
    I have a WBS delivery, when I use LT03 to create a TO by this delivery, I can see the WBS field is empty, and gray. how to let me go ahead to create a WBS TO?
    Thanks.

    If the LIPS fields don't have the special stock data, then your delivery is not related to special stock. Consequently, the TO cannot have special stock data too.
    If you expected that project stock should be picked and issued through the delivery, it's better you check the preceding documents, master data and configuration, something may have gone wrong.

  • How to use search index created by jhindexer

    Hi i have created a JavaHelp set using Docbook which works ok but the search doesnt work. I then discovered jhindexer and have sucessfully used it to create a directory called index containing the index (DOCs,DOCS.TAB etc) in the same directory as the html files but it still doesnt work.
    I guess i have to modify one off my javaHelp files (jhelpidx.xml,jhelpset.hs) to point to this index but cant find any info on this.
    Can anyne help me please.

    place the snippet below into your HelpSet File (.hs), the helpset file should be in the same directory as the JavaHelpSearch folder where your index files are located. See the structure:
    /foo.hs
    /JavaHelpSearch/DOCS
    /JavaHelpSearch/OFFSETS
    ---- snippet -----
    <view>
    <name>Search</name>
    <label>Suche</label>
    <type>javax.help.SearchView</type>
    <data engine="com.sun.java.help.search.DefaultSearchEngine">JavaHelpSearch</data>
    </view>
    ---- snippet -----
    And read the supplied PDF documentation, because if you have problems with this, you will have even more problems with some more advanced stuff.

Maybe you are looking for

  • Mail Will Not Receive After 10.6.2 Update

    I just updated to 10.6.2 and now my mail program will not receive any incoming emails. I seem to be able to send however. I'm sorry for another one of these "me too" postings about the mail program not working post update but I'm hoping Apple will se

  • Output Preview showing confused results

    Hello all, Please bear with me as I attempt to explain a very odd occurrence I am seeing in Acrobat X. Also, my assumption is that this is something in the authoring tool confusing Acrobat, as if I attempt this using only Adobe products I cannot repl

  • IMac not starting from internal drive

    Strange one this, iMac won't start from its own hard drive. It starts happily from an external drive, and other Macs are happy to start using this Mac (in target disc mode) as startup disc. So there doesn't seem to be anything wrong with the hard dri

  • Time Capsule - yellow blinks after internet source changed to wireless.

    I just got a wireless router from my internet provider (Telus).  My Time Capsule is blinking yellow.  I used to have ethernet cable in TC from Telus old router (via phone) but now all is wireless.  Where do I go on MBPro to change settings so TC blin

  • I started downloading a TV show a few days ago and now theres no pause button.

    I started to download a TV show a few days ago and now theres no pause button next to the download in itunes on my ipod and the download is taking up a lot of bandwith.