views:

59

answers:

4

How do I invoke a method (e.g. setter inside object class) on an already existing object using Java reflection?

+3  A: 

You have a great tutorial HERE.

thelost
+1  A: 

See the Reflection Trail.

Devon_C_Miller
+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
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