java中通过反射获取某个类中的所有方法信息

2 篇文章 0 订阅

话不多说先上代码:

package Reflecthelper;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * 
 * @author Saturn
 *
 */
class try1 { //测试的类
	public void send(String send) {
		System.out.println(send);
	}
}
public class getMethod {
	public static void main(String args[]) throws Exception {
		Class<?> cls = try1.class;
		Method methods[] = cls.getMethods();
		for (Method met : methods) {
			int mod = met.getModifiers();
			System.out.print(Modifier.toString(mod) + " ");           //先输出方法名字
			System.out.print(met.getReturnType().getName() + " ");
			System.out.print(met.getName() +  "(");
			Class<?> params[] = met.getParameterTypes();
			for (int x = 0; x < params.length; x ++) {
				System.out.print(params[x].getName() + " "  + "args-" + x);  //拼凑出方法要求的数据类型
				if (x < params.length - 1) {
					System.out.print(",");
					
				}
			}
			System.out.print(") ");
			Class<?> exp[] = met.getExceptionTypes();
			if (exp.length > 0) {
				System.out.print("throws ");  //获取其支持处理的异常信息
				
			}
			for (int x = 0 ; x < exp.length ; x ++) {
				System.out.print(exp[x].getName());
				if (x < exp.length - 1) {
					System.out.println(",");
				}
			}
			System.out.println(); //换行
		}
	}
}

结果:

public void send(java.lang.String args-0) 下面的都是object中继承的方法
public final void wait(long args-0,int args-1) throws java.lang.InterruptedException
public final void wait() throws java.lang.InterruptedException
public final native void wait(long args-0) throws java.lang.InterruptedException
public boolean equals(java.lang.Object args-0)
public java.lang.String toString()
public native int hashCode()
public final native java.lang.Class getClass()
public final native void notify()
public final native void notifyAll()

原理:
通过反射机制获取类中的所有方法,随后将获取的所有方法对象中的信息拼凑输出。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Spasol

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值