黑马程序员——JAVA笔记——JavaBean

JavaBean与内省访问技术详解
本文深入探讨了JavaBean的概念以及内省技术在操作JavaBean属性中的应用,包括使用PropertyDescriptor和IntroSpector实现属性的读取和修改。
部署运行你感兴趣的模型镜像

------- android培训java培训、期待与您交流! ----------


JavaBean:为一种特殊的类,类中大多为私有字段,并通过固定的名称,也就是set、get方法来操作信息。

IntroSpector(内省):为了更好的操作对象的属性而出现,有利于操作对象的属性,减少代码的书写。


内省访问JavaBean代码的方法有两种:

1、通过PropertyDescriptor来操作。

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

public class Demo1
{
	public static void main(String[] args) throws Exception
	{
		Student stu=new Student("zhangsan",22);
		String PropertyName="name";
		PropertyDescriptor pd=new PropertyDescriptor(PropertyName,Student.class);
		Method getMethod=pd.getReadMethod();
		Method setMethod=pd.getWriteMethod();
		Object name=getMethod.invoke(stu);
		System.out.println(name);
		setMethod.invoke(stu,"lisi");
		System.out.println(getMethod.invoke(stu));
	}
}

class Student{
	private String name;
	private int age;
	
	Student(String name,int age){
		this.name=name;
		this.age=age;
	}

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

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


2、通过IntroSpector中的getBeanInfo方法获取BeanInfo,再通过BeanInfo获取PropertyDescriptors,最后通过PropertyDescriptor获取信息。

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;

public class Demo1
{
	public static void main(String[] args) throws Exception
	{
		Student stu=new Student("zhangsan",22);
		String PropertyName="name";
		
		BeanInfo beaninfo = Introspector.getBeanInfo(Student.class);
		PropertyDescriptor[] pds = beaninfo.getPropertyDescriptors();
		for(PropertyDescriptor pd:pds){
			if(pd.getName().equals(PropertyName)){
				System.out.println(pd.getReadMethod().invoke(stu));
				break;
			}
		}
	}
}


class Student{
	private String name;
	private int age;
	
	Student(String name,int age){
		this.name=name;
		this.age=age;
	}

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

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


通过PropertyDescriptor获取信息的方法:

getName() 获得属性的名字。

getPropertyType() 获得属性的class对象;

getReadMethod() 获得用于读取属性值的方法;

getWriteMethod() 获得用于写入属性值的方法;

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值