How can I call a method on an object using the Reflection API?

How do I call a method (like a setter inside an object class) on an already existing object using Java reflection?

+2


a source to share


4 answers


Here's the way:



Object yourObject = ...;
Class clazz = yourObject.getClass();
Method setter = clazz.getMethod("setString", String.class); // You need to specify the parameter types
Object[] params = new Object[]{"New String"};
setter.invoke(this, params); // 'this' represents the class from were you calling that method.
// If you have a static method you can pass 'null' instead.

      

+3


a source


You have a great tutorial HERE .



+3


a source


+1


a source


You can do it,

Class cls = obj.getClass();
Method m = cls.getMethod("yourMethod", String.class); // assuming there is a method of signature yourMethod(String x);
m.invoke(obj, "strValue");

      

0


a source







All Articles