I need to invoke methods in a class (called Foo in this example) using only Strings. For example passing BigInteger class as argument is not an option in my case.
My code works fine, when I use java.lang.String, but if try with other types, like BigInteger for example a "java.lang.IllegalArgumentException: argument type mismatch" is thrown
This is the class I am testing the reflection against:
package com.test;
import java.math.BigInteger;
public class Foo {
private String name;
private BigInteger age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigInteger getAge() {
return age;
}
public void setAge(BigInteger age) {
this.age = age;
}
@Override
public String toString() {
return "Foo [name=" + name + ", age=" + age + "]";
}
}
My goal is to invoke setAge(BigInteger age) method using Java reflections. This is the code I use:
package com.main;
import java.lang.reflect.Method;
public class Run {
public static void main(String[] args) {
try {
Class clazz = Class.forName("com.test.Foo");
Object obj = clazz.newInstance();
Method m = clazz.getMethod("setAge", new Class[]
{Class.forName("java.math.BigInteger")});
m.invoke(obj, "12");
System.out.println("after method call " + obj.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Unfortunately after executing the code I get the java.lang.IllegalArgumentException.
To summarize my question: haw can I use arguments different than Strings using java reflections, given the type itself should be provided as String?
Aucun commentaire:
Enregistrer un commentaire