Gandalf StormCrow
Gandalf StormCrow

Reputation: 26212

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

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

Upvotes: 2

Views: 1089

Answers (4)

Phanindra
Phanindra

Reputation: 137

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");

Upvotes: 0

Martijn Courteaux
Martijn Courteaux

Reputation: 68907

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.

Upvotes: 2

Devon_C_Miller
Devon_C_Miller

Reputation: 16528

See the Reflection Trail.

Upvotes: 1

thelost
thelost

Reputation: 6694

You have a great tutorial HERE.

Upvotes: 3

Related Questions