JavaBean的概述与简单应用



       JavaBean 是一种JAVA语言写成的可重用组件。为写成JavaBean,类必须是具体的和公共的,并且具有无参数的构造器。JavaBean 通过提供符合一致性设计模式的公共方法将内部域暴露成员属性。众所周知,属性名称符合这种模式,其他Java 类可以通过自身机制发现和操作这些JavaBean 属性。

       简单的来说JavaBean是有get set方法的特殊的java类,比如

package com.itheima.shipin.javaBean;

public class Student {
	String name="heima";
	int 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;
	}

	
}

      上面创建了一个student类里面有姓名name,年龄age两种属性并且有相应的get和set方法给这两个属性读取和输出相应的值,并且其中我们默认给name取值为heima。以下对这个JavaBean做个简单的内行操作。

代码如下

package com.itheima.shipin.javaBean;

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

public class introspectorTest {

	public static void main(String[] args) throws Exception {

		Student student = new Student();
		String propertyName = "name";

		PropertyDescriptor pd = new PropertyDescriptor(propertyName,
				student.getClass());			//属性描述 
		Method metodGetName = pd.getReadMethod();
		Object retVal = metodGetName.invoke(student);
		System.out.println(retVal);
	}

}
运行结果

heima

对以上代码中的

		PropertyDescriptor pd = new PropertyDescriptor(propertyName,
				student.getClass());			//属性描述 
		Method metodGetName = pd.getReadMethod();
进行重构

package com.itheima.shipin.javaBean;

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

public class introspectorTest {

	public static void main(String[] args) throws Exception {

		Student student = new Student();
		String propertyName = "name";

		Object retVal = getPropertyName(student, propertyName);
		System.out.println(retVal);
	}

	private static Object getPropertyName(Student student, String propertyName)
			throws IntrospectionException, IllegalAccessException,
			InvocationTargetException {
		PropertyDescriptor pd = new PropertyDescriptor(propertyName,
				student.getClass());			//属性描述 
		Method metodGetName = pd.getReadMethod();
		Object retVal = metodGetName.invoke(student);
		return retVal;
	}

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值