如何使用Java反射在现有对象上调用方法(例如,对象类内的setter)?
答案 0 :(得分:3)
你有一个很棒的教程HERE。
答案 1 :(得分:3)
这是一种方式:
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.
答案 2 :(得分:1)
请参阅Reflection Trail。
答案 3 :(得分:0)
你可以这样做,
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");