How do I invoke a method (e.g. setter inside object class) on an already existing object using Java reflection?
+1
A:
Here is a 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.
Martijn Courteaux
2010-05-05 14:48:36
A:
You can do this,
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");
Phanindra
2010-05-05 14:49:06