反射--Method

     通过反射,可以获取方法等相关内容。

    示例如下:

1、实体类Emp2

public class Emp2 {

	public void m1(){
		System.out.println("this is a method with no parameter!");
	}
	
	public void m2(String s){
		System.out.println("this is a method with a String parameter, the value of the paramter is :" + s);
	}
	
	public static void m3(){
		System.out.println("this is a static method with not parameter!");
	}
}


2、调用

  (1)调用m1

Method m1 = Emp2.class.getMethod("m1",null);
m1.invoke(new Emp2(), null);

结果如下:

this is a method with no parameter!

  (2)调用m2

Method m2 = Emp2.class.getMethod("m2", String.class);
m2.invoke(new Emp2(), " yy");

结果如下:

this is a method with a String parameter, the value of the paramter is : yy

(3)调用m3

Method m3 = Emp2.class.getMethod("m3", null);
m3.invoke(null, null);

结果如下:

this is a static method with not parameter!

(4)获取m3返回值类型

System.out.println(m3.getReturnType());

结果如下:

void

 

可以看出:

对于static的方法,第一次参数可以传入null。

对于参数类型,若方法有参数,比如传入对应的类型。若没有,传入null。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值