内省

public class Student {
	//综上,这个类有三个属性
private String name;//字段
private int age;//字段
public String getName() {//属性指的是设置set和读取get字段的方法
	return name;
}
public void setName(String name) {
	this.name = name;
}
public int getAge() {
	return age;
}
public void setAge(int age) {
	this.age = age;
}
public String getAbc() {//属性名称是abc
	return "abc";
}
}

测试类:`package cn.itcast.base.enumou;

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

import javax.xml.ws.handler.MessageContext.Scope;

import org.junit.Test;

public class Demo1 {
//内省是操作属性的(类的getter和setter方法)
	//例如getClass()   它的属性是class   getAbc    是abc
	@Test
	public  void test1() throws Exception{
    //得到Student类中的属性,病封装到BeanInfo中去
		BeanInfo bi=Introspector.getBeanInfo(Student.class);
	//得到类中的所有属性描述器
		PropertyDescriptor[] pds=bi.getPropertyDescriptors();
		System.out.println(pds.length);
		for(PropertyDescriptor pd:pds) {
			System.out.println(pd.getName());
		}    
	}
}

打印结果如下:
4
abc
age
class
name
`
`注意:每个类都有一个默认属性。只要是Object类型,都有getClass()属性``
使用:
@Test
	public  void test2() throws Exception{
		Student student=new Student();
		PropertyDescriptor pDescriptor=new PropertyDescriptor("name", Student.class);
		Method method1=pDescriptor.getReadMethod();//得到get方法
		String string=(String)method1.invoke(student, null);
		Method method2=pDescriptor.getWriteMethod();
		method2.invoke(student, "高蒙");
	}
	

## 内省框架
 BeanUtils是Apache开发的一套快速操作JavaBean getter/setter方法的api,目前比较流行
 准备包:  commons-beanutils.jar    commons-logging.jar
 语法:
      设置:BeanUtils.setProperty(Object bean,String PropertyName,String PropertyValue);
      获取:BeanUtils.getProperty(Object bean,String PropertyName);

``	@Test
	public  void test3() throws Exception{
		Student student=new Student();
		//为什么要返回字符串,因为用户所有的输入都是字符串
		String string=BeanUtils.getProperty(student,"name");
		BeanUtils.setProperty(student,"name","高蒙");	
	}

****BeanUtils可以进行类型类型转换,但仅限基本类型(例如Date类型就不行)

之前说过,用户输入的都是字符串类型,所以就牵扯一个问题
字符串<--------------->其他类型之间的相互转换
所以需要给BeanUtils注册类型转换器

下面有更简单的![转换](https://img-blog.csdnimg.cn/20190825141250463.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2dtMTk5NDA0MDI=,size_16,colo
下面有更简单的实现
在这里插入图片描述
改版上述程序(选择已有的日期转换器)
在这里插入图片描述

额外注意的还有Map

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值