java反射一

来源:互联网 发布:sim900a调试软件 编辑:程序博客网 时间:2024/06/04 21:14

package com.zhouyuntao.reflexmethod;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflexMethodDemo {

 public String addMethod(String value) {
  return "hello:" + value;
 }

 public static void main(String[] args) throws ClassNotFoundException,
   SecurityException, NoSuchMethodException, InstantiationException,
   IllegalAccessException, IllegalArgumentException,
   InvocationTargetException {

  // 方式一:
  Class c = Class.forName("com.zhouyuntao.refexmethod.ReflexMethodDemo");// 包名+类名

  // 方式二:
  // Class c = ReflexMethodDemo.class;

  // 获得实例对象
  ReflexMethodDemo reflex = (ReflexMethodDemo) c.newInstance();

  // c.getMethod("你想要获得的方法的方法名称", new Class[]{方法的参数类型});
  Method addMethod = c.getMethod("addMethod",
    new Class[] { String.class });

  String str = (String) addMethod.invoke(reflex, new Object[] { "哈哈" });
  
  System.out.println(str);
  
 }

}

原创粉丝点击