反射(reflect)--获取字节码文件中的方法(函数)

public class Person {

	private int age;
	private String name;
	
	public Person(String name,int age) {
		super();
		this.age = age;
		this.name = name;
		System.out.println("Person param run..."+this.name+":"+this.age);
	
	}
	public Person() {
		super();
		System.out.println("person run");
	}
	
	public void show(){
		System.out.println(name+"...show run..."+age);
	}
	
	private void privateMethod(){
		System.out.println(" method run ");
	}
	
	public void paramMethod(String str,int num){
		System.out.println("paramMethod run....."+str+":"+num);
		
	}
	public static void staticMethod(){
		System.out.println(" static method run......");
	}
}

public class ReflectDemo4 {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		getMethodDemo_3();
	}

	public static void getMethodDemo_3() throws Exception {
		
		Class clazz = Class.forName("cn.itcast.bean.Person");
		
		Method method = clazz.getMethod("paramMethod", String.class,int.class);
		
		Object obj = clazz.newInstance();
		
		method.invoke(obj, "小强",89);
		
	}

	public static void getMethodDemo_2() throws Exception {
		
		Class clazz = Class.forName("cn.itcast.bean.Person");
		
		Method method = clazz.getMethod("show", null);//获取空参数一般方法。
//		Object obj = clazz.newInstance();
		Constructor constructor = clazz.getConstructor(String.class,int.class);
		Object obj = constructor.newInstance("小明",37);
		
		method.invoke(obj, null);
	}

	/*
	 * 获取指定Class中的所有公共函数。
	 */
	public static void getMethodDemo() throws Exception {
		
		Class clazz = Class.forName("cn.itcast.bean.Person");
		
		Method[] methods  = clazz.getMethods();//获取的都是公有的方法。 
		methods = clazz.getDeclaredMethods();//只获取本类中所有方法,包含私有。 
		for(Method method : methods){
			System.out.println(method);
		}
		
		
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值