Java Generics and reflection!

13,232

Solution 1

The constructor is protected - if you make it public or use getDeclaredConstructor instead of getConstructor it should work.

(You'll need to use setAccessible if you're trying to call this from somewhere you wouldn't normally have access.)

EDIT: Here's a test to show it working okay:

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

public class UploadBean {

    // "throws Exception" just for simplicity. Not nice normally!
    public static void main(String[] args) throws Exception {
        Class<?> parTypes[] = new Class<?>[1];
        parTypes[0] = Map.class;
        Constructor ct = UploadBean.class.getDeclaredConstructor(parTypes);
        Object[] argList  = new Object[1];
        argList[0] = null;
        Object retObj = ct.newInstance(argList);
    }

    protected UploadBean(Map<String,?> map){ 
        //do nothing.
    }
}

Solution 2

The generic information is not available at runtime, it's just for static analysis, so do it as if the generics didn't exist.

Share:
13,232
Jay
Author by

Jay

geek, software developer, movie buff and pirate.

Updated on June 18, 2022

Comments

  • Jay
    Jay over 1 year

    I have a class that looks like this:

    public class UploadBean {
    
    
        protected UploadBean(Map<String,?> map){ 
            //do nothing.
        }
    }
    

    To use reflection and create a object by invoking the corresponding constructor, I wrote code as follows:

    Class<?> parTypes[] = new Class<?>[1];
    parTypes[0] = Map.class;
    Constructor ct = format.getMappingBean().getConstructor(parTypes);
    Object[] argList  = new Object[1];
    argList[0] = map;
    Object retObj = ct.newInstance(argList);
    

    This code fails at runtime with "No Such Method Exception". Now, how do I set the param type correctly?! such that the generic map argument in the constructor is identified?

  • palantus
    palantus over 14 years
    Or use getDeclaredConstructor(), as I just found out (but too late!).
  • Jay
    Jay over 14 years
    doesn't work throws this exception again: java.lang.NoSuchMethodException: test.fileupload.XYZUploadBean.<init>(java.util.Map)
  • Jon Skeet
    Jon Skeet over 14 years
    @Jay: Please provide a short but complete program then. If you're using the right class and it's got the right constructor, it should be okay. It works in my tests.
  • Jon Skeet
    Jon Skeet over 14 years
    In particular, does XYZUploadBean have the right constructor? You've shown UploadBean, but not XYZUploadBean...
  • palantus
    palantus over 14 years
    Yeah, the error really has nothing to do with generics; this is really just a reflection question. (But it's nice to clarify this point.)