Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics and reflection!

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?

like image 345
Jay Avatar asked Jun 02 '09 14:06

Jay


2 Answers

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.
    }
}
like image 199
Jon Skeet Avatar answered Oct 19 '22 16:10

Jon Skeet


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

like image 21
fortran Avatar answered Oct 19 '22 16:10

fortran