Java.lang.reflect.Method invoke方法 实例
2012-02-17 09:03
375 查看
import java.lang.reflect.Method; /** * Java.lang.reflect.Method invoke方法 实例 * 程序中配置文件中有对实体对象的get,set方法的描述,通过应用invoke()方法调用实体对象的method方法 return * m_oGetter.invoke(oSrc, null); oSrc为实体对象,Method m_oGetter * 这里的m_oGetter是对应于在代理实例(oSrc)上调用的接口方法的 Method 实例,下面参考示例代码 * */ class Employee { // 定义一个员工类 public Employee() { age = 0; name = null; } // 将要被调用的方法 public void setAge(int a) { age = a; } // 将要被调用的方法 public int getAge() { return age; } // 将要被调用的方法 public void printName(String n) { name = n; System.out.println("The Employee Name is: " + name); } private int age; private String name; } public class InvokeMethods { public static void main(String[] args) { Employee emp = new Employee(); Class<?> cl = emp.getClass(); // /getClass获得emp对象所属的类型的对象,Class就是类的类 // /Class是专门用来描述类的类,比如描述某个类有那些字段, // /方法,构造器等等! try { // /getMethod方法第一个参数指定一个需要调用的方法名称 // /这里是Employee类的setAge方法,第二个参数是需要调用 // 方法的参数类型列表,是参数类型!如无参数可以指定null // /该方法返回一个方法对象 Method sAge = cl.getMethod("setAge", new Class[] { int.class }); Method gAge = cl.getMethod("getAge", null); Method pName = cl.getMethod("printName", new Class[] { String.class }); /** *使用invoke调用指定的方法 */ Object[] args1 = { new Integer(25) }; // 参数列表 // emp为隐式参数该方法不是静态方法必须指定 sAge.invoke(emp, args1); Integer AGE = (Integer) gAge.invoke(emp, null); int age = age .intValue(); System.out.println("The Employee Age is: " + age); Object[] args3 = { new String("Jack") }; pName.invoke(emp, args3); } catch (Exception e) { e.printStackTrace(); } System.exit(0); } }
相关文章推荐
- Java.lang.reflect.Method invoke方法 实例
- (转)Java.lang.reflect.Method invoke方法 实例
- Java.lang.reflect.Method invoke方法 实例
- Java.lang.reflect.Method invoke
- Java.lang.reflect 下的Class,Method,Field的使用实例
- java.lang.Method.invoke方法使用
- java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0
- 使用java反射中的getMethod,invoke方法调用对象方法的实例
- java反射Method中的如何调用任意方法,即invoke()的使用
- 解决Attempt to invoke virtual method'boolean java.lang.String.equals(java.lang.Object)'...
- java.lang.Throwable.getCause()方法实例
- android JPushInterface.setAlias 报错 java.lang.NullPointerException: Attempt to invoke virtual method
- during initialization of VM java/lang/NoClassDefFoundError: java/lang/invoke/MethodHandle
- 解决Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null···
- caused by NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(ja
- Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null objec
- 在三大框架里运用lucene和ik分词是报java.lang.reflect.InvocationTargetException异常的解决方法
- JAVA反射系列之Field,java.lang.reflect.Field使用获取方法。
- lPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.
- JAVA深入研究——Method的Invoke方法(转)