关于类的反射机制的实现

就我目前看的资料有两种实现手段:
 1)利用java.lang.reflect.*中的类和接口,相信大家都很熟啦!
 2)主要是利用java.beans.*中的BeanInfo接口和Introsepector类,Demo如下:
操作的JAVABEAN:
package me.jdk.reflect;
public class JavaBean {

 private String name;

 private String password;

 /**
  * @return Returns the name.
  */
 public String getName() {
  return name;
 }

 /**
  * @param name The name to set.
  */
 public void setName(String name) {
  this.name = name;
 }

 /**
  * @return Returns the password.
  */
 public String getPassword() {
  return password;
 }

 /**
  * @param password The password to set.
  */
 public void setPassword(String password) {
  this.password = password;
 }

 /**
  *
  */
 public JavaBean() {
  // TODO Auto-generated constructor stub
 }

}
实现内现的类:
/**
 *
 */
package me.jdk.reflect;
import java.beans.BeanDescriptor;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.util.Enumeration;

/**
 * 功能描述:实现Introsepector
 * @create on: 2006-12-15
 */
public class MyReflect<E> {

 /**
  *
  */
 public MyReflect() {
  // TODO Auto-generated constructor stub
  
 }
 
 public void testReflect(Class cls) {
  BeanInfo info = null;
  try {
   info = Introspector.getBeanInfo(cls,Object.class);
   PropertyDescriptor[] properties = info.getPropertyDescriptors();
   for(int i = 0; i < properties.length; i++ )
    System.out.println("properties["+i+"].getName()"+properties[i].getName());                                            
   MethodDescriptor[] methods = info.getMethodDescriptors();
   for(int j = 0; j < methods.length; j++)
    System.out.println("methods["+j+"].getName()"+methods[j].getName());
   }
   
  } catch (IntrospectionException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 /*
  *@return_type void
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  MyReflect reflect = new MyReflect();
  reflect.testReflect(me.jdk.reflect.JavaBean.class);
 }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值