lundi 23 novembre 2015

How can I get a Class object form primitive? [duplicate]

This question already has an answer here:

Obviously this is possible (as Class has isPrimitive() method) but how I can do this directly? E.g. reflection api able to cast a primitive type to Class:

import java.lang.reflect.Method;


public class TestClass {

        public static void m(){}
        public static void m(Object o){}
        public static void m(int i){}
        public static void m(Integer i){}

        public static void main(String[] args){

                TestClass tc=new TestClass();
                Method[] mtds=tc.getClass().getDeclaredMethods();

                for (int i = 0; i < mtds.length; i++) {
                        System.out.print(mtds[i].getName());
                        Class[] prms=mtds[i].getParameterTypes();
                        for (int j = 0; j < prms.length; j++) {
                                System.out.print("-"+prms[j].getCanonicalName());

                        }
                        System.out.println();
                }        
        }
}

output is:

m

m-java.lang.Object

m-int

m-java.lang.Integer

main-java.lang.String[]

Integer and int are different so it is not autoboxing. Anything (except creating an utility class with reflection and getParameterTypes() ) do not come at my mind (everything else I've tried failed).





Aucun commentaire:

Enregistrer un commentaire