反射加载获取类class方法与return返回类型,new创建实例,获取某个固定方法method

通过反射技术加载出Class里面的方法

public static void main(String[] args) throws Exception
	{
		// 参数:指定为目标类的路径
		Class cls = Class.forName("af.test.Example");
		
		Method[] methods = cls.getDeclaredMethods();
		for(Method m : methods)
		{
			String name = m.getName();
			Type type = m.getReturnType();
			System.out.println(name + ", " + type.getTypeName());
		}
	}

	//样例输出
	/*	test3, void
		test5, double
		test1, void
	*/

通过反射技术创建一个实例

public static void main(String[] args) throws Exception
	{
		// 参数:指定为目标类的路径
		Class cls = Class.forName("my.Student");
		
		Object obj = cls.newInstance();
		
		System.out.println("Exit.");
	}

类的方法

public static void main(String[] args) throws Exception
	{
		//获取类
		Class cls = Student.class;
		Method[] methods = cls.getDeclaredMethods();
		//遍历所有方法
		for(Method m : methods)
		{
			//获取方法名
			String name = m.getName();
			//获取方法的类型
			Class returnType = m.getReturnType();
			//获取调用方法需要的类型
			Class[] paramTypes = m.getParameterTypes();
			
			//打印出来的方法的描述
			System.out.print("- " + returnType.getSimpleName()
					+ " " + name + "(");
			
			for(int i=0; i<paramTypes.length; i++)
			{
				Class param = paramTypes[i];
				System.out.print(param.getSimpleName());
				if(i < paramTypes.length-1)
					System.out.println(", ");
			}
			System.out.println(")");
		}
		System.out.println("Exit.");
	}

	/*
		打印参考:
		- Integer getId()
		- void setName(String) 
	*/

获取一个方法

package my;

import java.lang.reflect.Type;

import af.test.Example;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test
{
	public static Method getMethod(Method[] methods, String name)
	{
		for(Method m : methods)
		{
			if(m.getName().equals(name))
				return m;
		}
		return null;
	}
	
	public static void main(String[] args) throws Exception
	{
		//从example.jar中加载一个类
		Class cls = Class.forName("af.test.Example");
		
		// 获取该类的方法
		Method[] methods = cls.getDeclaredMethods();
		
		// 按名称遍历查找 (要求没有重名的方法)
		Method testMethod = getMethod(methods, "test1");
			
		System.out.println("Exit.");
	}
}                                     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值