内省机制(Introspector)

一 内省机制

 

Introspector:内省/自省:获取和操作JavaBean中的属性.

操作JavaBean的属性:

              1):获取属性相关信息.属性名,属性类型

              2):给属性设置数据,调用setter方法.

              3):获取属性的数据,调用getter方法.

 

 

 

package com.OSA.Day01.JavaBean_02;

public class User_01 {

	private String name;
	private Integer age;
	private boolean man;

	// 遵守编写get规范 生成属性

	// 生成属性name

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	// 生成属性age
	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	// 生成属性man
	public boolean isMan() {
		return man;
	}

	public void setMan(boolean man) {
		this.man = man;
	}
	
	
	//属性不一定和字段同时存在 只要属性 fullName,但是没有改字段
	public void setFullName(String fullName){
		
	}
	
	

}

 

 

 

 

 

package com.OSA.Day01.JavaBean_02;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class IntrospectorDemo_03 {

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		// 获取所有的属性包括父类的

//		BeanInfo beaninfo = Introspector.getBeanInfo(User_01.class);
		
//		到Object这层停止获取
		BeanInfo beaninfo = Introspector.getBeanInfo(User_01.class,Object.class);

		
		PropertyDescriptor[] propertyDescriptors = beaninfo
				.getPropertyDescriptors();

		
		for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {

			// 获取属性的名称
			String name = propertyDescriptor.getName();
			System.out.println(name);

			// 获取属性的类型
			Class type = propertyDescriptor.getPropertyType();
			System.out.println(type);

			// 获取所有的读方法
			Method getter = propertyDescriptor.getReadMethod();
			System.out.println(getter);

			// 获取写得方法
			Method setter = propertyDescriptor.getWriteMethod();
			System.out.println(setter);

		}

	}

}

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值