开发者

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

开发者 https://www.devze.com 2022-12-29 20:04 出处:网络
How do I invoke a method (e.g. setter inside object class) on an already existing object using J开发者_JS百科ava reflection?You have a great tutorial HERE.Here is a way:

How do I invoke a method (e.g. setter inside object class) on an already existing object using J开发者_JS百科ava reflection?


You have a great tutorial HERE.


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.


See the Reflection Trail.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号