Java Generics and Thoughts!

I have a class that looks like this:

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

To use reflection and create an object by calling the appropriate constructor, I wrote the 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 crashes at runtime with a "No Such Method Exception". Now, how did I configure the parameter correctly? so what is the general argument of the map identified in the constructor?

+4
source share
3 answers

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

(You need to use setAccessible , if you are trying to call it from somewhere, you usually do not have access.)

EDIT: Here's a test to show that it works fine:

 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. } } 
+7
source

General information is not available at runtime, it's just for static analysis, so make it as if generics do not exist.

+1
source

I think you need to call

 ct.setAccessible(true) 

The setAccessible method allows you to override access methods.

0
source

All Articles