反射机制

本文介绍了Java中反射机制的基本用法,包括通过类名获取类实例、调用类的方法等,并展示了如何使用Introspector进行JavaBean的自省操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public Object myInvoke(String className, String methodName, Object args[]) {
	Object results = null;
	try {
		Class clazz = Class.forName(className);
		Method method = null;
		for (int i = 0; i < clazz.getMethods().length; i++) {
			method = clazz.getMethods()[i];
			if(methodName.equals(method.getName())) {
				results = method.invoke(clazz.newInstance(), args);
				break;
			}
		}
	} catch (Exception e) {		
		e.printStackTrace();
	}
	return results;
}

 反射常用的几种方法(前面是返回类型后面是方法名)

         获取构造函数 

  1.Constractor        getConstrator(Class[] parameterTypes);

   2.Constrator[]       getConstators();

          获取方法

  1,Method     getMethod(String name, Class[] parameterTypes)

  2.Method[]     getMethods();

           获取属性

 1.Filed       getFiled(String name);

 2.Fileds     getFileds();

       检查特性

1.Class[] getInterfaces() 、Package getPackage() 、boolean isArray() 、boolean isInterface()

 

   --------------------------------------------------------------------------------------------------------------------

自省机制是使用Introspector实现的。
Introspector的方法大部分都是静态的,可以直接调用,如getBeanInfo(Class beanClass) 可以得到一个JavaBean的BeanInfo实例。
BeanInfo实例包含了一个JavaBean类属性和方法的信息。如:
BeanDescriptor getBeanDescriptor()
MethodDescriptor[] getMethodDescriptors()
PropertyDescriptor[] getPropertyDescriptors()

PropertyDescriptor 代表了属性,可以通过它得到属性的getter方法和setter方法。即:
Method getReadMethod()
Method getWriteMethod()

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值