Java之反射机制【入门版(4),实例解析】

import java.lang.reflect.Method;

public class MethodReflectDemo1 {
	public static void main(String[] args) {
		/*获取方法对象----》某个方法
		 * 获取一个方法应该由方法名称和参数列表来决定
		 * */
		MethodTest mt = new MethodTest();
		Class c = mt.getClass();
		try {
			Method method = c.getMethod("f", 
					new Class[]{int.class,int.class });
			mt.f(10, 10);
			System.out.println("++++++++++++++++++++++++++++++");

			/*能不能够直接通过method对象直接调用方法
			 * 效果和mt.f(10,10)等价
			 * 这就是方法反射要做的
			 * method.invoke(操作对象,参数);
			 * */
			method.invoke(mt, new Object[]{10,10});
			System.out.println("+++++++++++++++++++++++++++++++++++");
			Method method2 = c.getMethod("f",
					new Class[]{int.class,int.class,int.class});
			System.out.println(mt.f(10,10,10));
			//通过method2直接操作
			int result =(Integer) method2.invoke(mt, new Object[]{10,10,10});
			System.out.println(result);


			System.out.println("+++++++++++++++++++++++++++++++++++");
			String s1 = "hello";
			String s2 = "world";
			System.out.println(s1.concat(s2));
			/*
			 * 用concat方法的反射来操作
			 * 首先获取String类类型
			 * 
			 * */
			Class c1 = String.class;
			//获取concat
			Method concatMethod = c1.getMethod("concat",
					new Class[]{String.class});
			String ss = (String)concatMethod.invoke(s1, new Object[]{s2});
			System.out.println(ss);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
}
class MethodTest{
	public void f(int a,int b){
		System.out.println(a+b);
	}
	public int f(int a,int b,int c){
		System.out.println("三个数加");
		return a+b+c;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值