反射机制--获取Class中的方法

package text;

import java.lang.reflect.Method;

public class ReflectDemo4 {

	public static void main(String[] args) throws Exception {
		getMethodDemo();
	}

	/*
	 * 获取指定Class中所有的公共函数
	 * */
	public static void getMethodDemo() throws Exception{
		Class clazz=Class.forName("text.Person");

		//getMethods()返回一个方法数组
		Method[] methods= clazz.getMethods(); //获取的都是公有的方法(包含父类的方法),没有获取到Person类私有方法method()
		
//		methods=clazz.getDeclaredMethods(); //只获取本类中所有方法,包含私有
		
		for(Method method:methods){
			System.out.println(method);
		}
	} 
}

运行结果:


可以看到,方法中也出现了父类的方法,并且所有的方法都是公有的。那么如何获取类中的私有方法呢?

package text;

import java.lang.reflect.Method;

public class ReflectDemo4 {

	public static void main(String[] args) throws Exception {
		getMethodDemo();
	}

	/*
	 * 获取指定Class中所有的公共函数
	 * */
	public static void getMethodDemo() throws Exception{
		Class clazz=Class.forName("text.Person");

		//getMethods()返回一个方法数组
		Method[] methods= clazz.getMethods(); //获取的都是公有的方法(包含父类的方法),没有获取到Person类私有方法method()
		
		methods=clazz.getDeclaredMethods(); //只获取本类中所有方法,包含私有
		
		for(Method method:methods){
			System.out.println(method);
		}
	} 
}

运行结果:



上例演示了获取Class中的所有方法,下面演示获取一个方法:

package text;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class ReflectDemo4 {

	public static void main(String[] args) throws Exception {
		getMethodDemo_2();
	}
	
	public static void getMethodDemo_2() throws Exception{
		Class clazz=Class.forName("text.Person");
		
		Method method= clazz.getMethod("show",null);  //获取空参数的show()方法
		
//		Object obj=clazz.newInstance();  //创建一个对象来运行show()方法(无参的构造方法)
		
		//使用有参的构造方法来创建对象
		Constructor constructor =clazz.getConstructor(int.class,String.class);
		Object obj=constructor.newInstance(37,"小明");
	
		
		method.invoke(obj, null);
	}	
}
运行结果:


在这里我们演示的是获取没有参数的方法,接下来我们再演示获取有参数的方法:

package text;

import java.lang.reflect.Method;

public class ReflectDemo4 {

	public static void main(String[] args) throws Exception {
		getMethodDemo_3();
	}
	
	public static void getMethodDemo_3() throws Exception{
		Class clazz=Class.forName("text.Person");
	
		Method method= clazz.getMethod("paramMethod",String.class,int.class); //获取参数列表为String,int的paramMethod方法
		
		Object obj=clazz.newInstance();  //创建一个对象来运行paramMethod方法
		
		method.invoke(obj, "小强",89);
	}
}

运行结果:


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值