Java 如何使用反射API对对象调用方法?

Java 如何使用反射API对对象调用方法?,java,reflection,Java,Reflection,如何使用Java反射在已经存在的对象上调用方法(例如对象类中的setter)?您有一个很棒的教程。请参阅。以下是一种方法: Object yourObject = ...; Class clazz = yourObject.getClass(); Method setter = clazz.getMethod("setString", String.class); // You need to specify the parameter types Object[] params = new O

如何使用Java反射在已经存在的对象上调用方法(例如对象类中的setter)?

您有一个很棒的教程。

请参阅。

以下是一种方法:

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.
你可以这样做

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