java 内省机制(工厂模式再次解耦)


反射——内省机制:javaBean


Bean:组件

javaBean:java组件

条件:

类必须是具体的和公有的

并且具有无参数的构造器

给定的所有属性必须私有,提供get和set方法,设置get与set方式时,属性名第一个字母要大写,然后加上get与set


我们可以通过内省机制操作javaBean属性


IntroSpector:内省


定义:

1.内省是java对Bean类属性、事件的一种缺省的处理机制。

2.通过反射的方式操作javaBean属性。


例如:Student类中有name属性,可以通过反射调用Student中的get与set方法。


补充:java的API中提供访问bean的get与set方法接口,存在java.bean包


内省机制的实现:


1.IntroSpector的静态方法getBeanInfo,获取BeanInfo对象信息。

2.通过BeanInfo对象调用getPropertyDescriptors获取PropertyDescriptor,就可以获取bean的所有属性描述了。

3.调用getWriteMethod与getReadMethod获取当前属性的get与set机制函数。


关联配置文件(properties文件):


1.properties文件

2.java.util.Properties类

3.类名.class.getResourceAsStream("文件路径");


配置文件的相关函数:


1.load函数:加载properties文件

2.getProperty函数:获取properties文件字段属性



代码实现内省机制:




工厂模式加入内省机制(再次解耦):

创建一个配置文件(Properties)的对象,然后关联程序

	private static Properties properties = new Properties();//定义一个Properties对象(配置文件对象)
	static{//静态块加载配置属性
		try{
			//创建流关联配置文件(工厂对象获取流输入)
			InputStream ins = Factory.class.getResourceAsStream("People.properties");
			//加载进入对象
			properties.load(ins);
		}catch(Exception e){
			e.printStackTrace();
		}
	}


工厂模式的创建对象方法中,加入自省机制实现创建对象和赋初值,因为代码中不再出现对象的类名对象名与方法名,所有工厂与程序之间的耦合度大大降低,只与配置文件由比较大的关联。

新增代码有注释:

	public static People getPeople(String type){
		try {
			//配置文件是以键值对的方式存取数据
			String value = properties.getProperty(type);
			People obj = (People) Class.forName(value).newInstance();
			BeanInfo beanInfo = Introspector.getBeanInfo(Class.forName(value));//获取javaBean对象用于自省方式赋值
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();//获取对象所有属性描述
			if("tea".equals(type)){
				for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {//遍历属性描述
					if("name".equals(propertyDescriptor.getName())){
						Method method = propertyDescriptor.getWriteMethod();//获取属性的set方法
						method.invoke(obj, properties.getProperty("name1"));//执行set方法
					}else if("age".equals(propertyDescriptor.getName())){
						Method method = propertyDescriptor.getWriteMethod();
						method.invoke(obj, Integer.parseInt(properties.getProperty("age1")));
					}
				}
			}else if("stu".equals(type)){
				for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
					if("name".equals(propertyDescriptor.getName())){
						Method method = propertyDescriptor.getWriteMethod();
						method.invoke(obj, properties.getProperty("name2"));
					}else if("age".equals(propertyDescriptor.getName())){
						Method method = propertyDescriptor.getWriteMethod();
						method.invoke(obj, Integer.parseInt(properties.getProperty("age2")));
					}
				}
			}
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null; 
	}

配置文件内容和程序的输出:



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值