简体   繁体   中英

Reflection: invoke a method using Number as wrapper for premitives

My task is to call the methods of java.lang.Math using a String with the necessary information. Since there are only methods using primitive number types I use Number as a wrapper, which then gets the value parsed from String.

Number value = null;
    switch (attributClass) {
        [...]//parse the attribute into "value"
    }
Method m = null;
try{
    m = Class.forName("java.lang.Math").getDeclaredMethod(mName, value.getClass());
...

now my problem is that I get the following exception:

java.lang.NoSuchMethodException: java.lang.Math.acos(java.lang.Double) at java.lang.Class.getDeclaredMethod(Unknown Source)

I suppose this happens because Double is not the primitive type double but is there any way to get the primitive from the Number?

There's no standard method for converting wrapper classes to primitive classes an vice versa to my knowledge.

A hacky way to get the primitive class of a wrapper class is wrapperClass.getDeclaredField("TYPE").get(null) (Because each wrapper defines such a field). If you don't want to do that you can create a Map<Class, Class> to map from wrappers to primitives and fill it with the 8 primitive types and their respective wrappers.

这似乎不那么明显,但是您可以使用primitive.class ,例如

m = Class.forName("java.lang.Math").getDeclaredMethod("min", int.class, int.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM