0610-----反射reflect

package com.itcast.reflect;

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

public class ReflectTest {

 public static void getEmployeeAllFieldNames(){
  Employee employee = new Employee();
  
  //get all the fields in the Employee
  Field[]fields = employee.getClass().getDeclaredFields();
  
  for(Field field:fields){
   //employee(object)-----Employee(class)-----Field[]--------field name
   String fieldName = field.getName();
   System.out.println("/t"+fieldName);
  }
  
 
  Class tempClass = employee.getClass();
  do{
    
     Field[]superClassFields = tempClass.getDeclaredFields(); 
     for(Field field:superClassFields){
    //employee(object)-----Employee(class)-----Field[]--------field name
    String fieldName = field.getName();
    System.out.println("/t"+fieldName);
   }
        tempClass = tempClass.getSuperclass();
  }while(tempClass != null);
  
 }
 
 
 public static void getEmployeeAllMethods(){
  Method[]methods = Employee.class.getDeclaredMethods();
  
  for(Method method:methods){
   System.out.println("/t"+method.getName());
  }
 }
 
 public static String getClassName(Object obj){
  Class clazz = obj.getClass();
  return clazz.getName();
 }
 /**
  * @param args
  */
 public static void main(String[] args) {
//  String str = "";
//  System.out.println(getClassName(str));

  getEmployeeAllFieldNames();
  
  //getEmployeeAllMethods();
  
  
  //load a class byte code into the JVM (Java virtual machine)
  try {
   Class.forName("com.itcast.reflect").newInstance();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }

}
获取javabean中的方法名,方法,super的方法..

 step1: 将类加载到java虚拟机

 step2:获取对象的所以的方法

 Field[] field =employee.getClass().getDeclareFields();

 

 //employee(object)-----Employee(class)-----Field[]--------field name

 

Introspector获取javabean的方法

//Introspector ----BeanInfo-----PropertyDescriptor-------property name

代码:

BeanInfo beanInfo = Introspector.getBeanInfo(Employee.class);
   
   PropertyDescriptor[]propertyDesccriptors = beanInfo.getPropertyDescriptors();
  
      for(PropertyDescriptor propertyDescriptor:propertyDesccriptors){
       System.out.print(propertyDescriptor.getName()+"/t");
       System.out.println(propertyDescriptor.getPropertyType()+"/t");
       System.out.println(propertyDescriptor.getReadMethod());

      }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值