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?
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.
}
}
The generic information is not available at runtime, it's just for static analysis, so do it as if the generics didn't exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With