views:

1623

answers:

3

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?

+3  A: 

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.
    }
}
Jon Skeet
Or use getDeclaredConstructor(), as I just found out (but too late!).
Michael Myers
doesn't work throws this exception again: java.lang.NoSuchMethodException: test.fileupload.XYZUploadBean.<init>(java.util.Map)
Jay
Would getDeclaredConstructor() then require setAccessible(true)? In my tests it doesn't, but I didn't try separating main() from the UploadBean.
Michael Myers
@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
In particular, does XYZUploadBean have the right constructor? You've shown UploadBean, but not XYZUploadBean...
Jon Skeet
Thanks, doing a getDeclaredConstructor worked.
Jay
A: 

I believe you need to call

ct.setAccessible(true)

The setAccessible method allows you to override access methods.

Rob Di Marco
A: 

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

fortran
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.)
Michael Myers
@mmyers agreed.
Jay