java 封装 方法_几种封装javaBean的方法

开发框架时,经常需要使用java对象(javaBean)的属性来封装程序的数据,封装javaBean的方法有很多,比如反射,内省,以及使用工具类。下面从反射开始介绍。

1.javaBean介绍:

简介:

JavaBean是使用Java语言开发的一个可重用的组件,在开发中可以使用JavaBean减少重复代码,使整个代码的开发更简洁。

编写要求:

javaBean本身是一个类,设计该类的时候要遵循一下方法:

1.如果成员变量的名字是xxx,则相应地有两个用来得到成员变量值和设置变量值的方法,它们分别是getXxx()和setXxx()且是public的:

public datatype getXxx();

public void setXxx(datatype data);

(2)如果成员变量是boolean型数据,使用is代替get方法;:

public boolean isXxx();

(3)需要一个无参数的构造函数。

一个javaBean的例子:

//javaBean

public class Person {

private int id;

private String name;

public Person(int id, String name) {

super();

this.id = id;

this.name = name;

}

//无参数构造函数

public Person(){}

//获得Id属性

public int getId() {

return id;

}

//设置

public void setId(int id) {

this.id = id;

}

//get方法

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

//tostring不在要求之中;

@Override

public String toString() {

return "id:"+ this.id+" name:"+ this.name;

}

}

2.使用反射封装JavaBean:

通过反射更改对象域来封装JavaBean,通过getDeclaredField方法获得对应的域,并调用set方法进行修改。

下面的方法通过配置文件更改JavaBean的属性:

配置文件内容如下:obj.txt

com.rlovep.bean.Person

id=22

name=peace

代码与注释:

public class CofigRef {

public static void main(String[] args) {

try {

//获得更改后的对象;

Person p=(Person)getInstance();

System.out.println(p);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

//根据配置文件的内容生产对象的对象并且要把对象的属性值封装到对象中。

public static Object getInstance() throws Exception{

//通过字符流进行输入;

BufferedReader bufferedReader = new BufferedReader(new FileReader("obj.txt"));

String className = bufferedReader.readLine(); //读取配置文件获取到完整的类名。

Class clazz = Class.forName(className);

//通过class对象获取到无参的构造方法

Constructor constructor = clazz.getConstructor(null);

//创建对象

Object o = constructor.newInstance(null);

//读取属性值

String line = null;

while((line = bufferedReader.readLine())!=null){

String[] datas = line.split("=");

//通过属性名获取到对应的Field对象。

Field field = clazz.getDeclaredField(datas[0]);

field.setAccessible(true);

if(field.getType()==int.class){

//更改属性内容;

field.set(o, Integer.parseInt(datas[1]));

}else{

field.set(o, datas[1]);

}

}

bufferedReader.close();

return o;

}

此去用反射进行更改,直接更改实现域的值;比较麻烦。需要各种判断和操作,不适合用于开发。

3.通过内省封装JavaBean:

内省(Introspector) 是Java 语言对 JavaBean 类属性、事件的一种缺省处理方法。Java JDK中提供了一套 API 用来访问某个属性的 getter/setter 方法,这就是内省。

1. PropertyDescriptor类:

属性描述器类,利用该类可以获得对应属性的get和set方法。

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

演示如下:

//属性描述器

PropertyDescriptor descriptor = new PropertyDescriptor("id", Person.class);

//获取属性对应的get或者是set方法设置或者获取属性了。

Method m = descriptor.getWriteMethod(); //获取属性的set方法。

//执行该方法设置属性值

m.invoke(p,110);

//获得get方法;

Method readMethod = descriptor.getReadMethod(); //是获取属性的get方法

System.out.println(readMethod.invoke(p, null));

Introspector类:

通过调用Introspector.getBeanInfo(People.class)方法可以获得BeanInfo对象,改对象封装了people类的所有属性。

而BeanInfo中有方法 getPropertyDescriptors(),获得属性的描述PropertyDescriptor[],可以通过遍历返回结果可以操作JavaBean。演示如下:

//Introspector 内省类

BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);

//通过BeanInfo获取所有的属性描述

PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); //获取一个类中的所有属性描述器

for(PropertyDescriptor p : descriptors){

//获得所有get方法

System.out.println(p.getReadMethod()); //get方法

}

通过这两个类的比较可以看出,都是需要获得PropertyDescriptor,只是方式不一样:前者通过创建对象直接获得,后者需要遍历,所以使用PropertyDescriptor类更加方便。

内省封装比反射相对来说简单点,但是实质上是反射的一种变体。

4利用BeanUtils封装JavaBean

介绍:

每次都使用反射技术完成此类操作过于麻烦,所以Apache开发了一套简单、易用的API来操作Bean的属性–BeanUtils工具包。

注意:应用的时候还需要一个logging

BeanUtils下载地址:链接

logging下载地址:链接

使用BeanUtils:

BeanUtils主要解决 的问题: 把对象的属性数据封装 到对象中。

属性值从配置文件中获取时可能都是String类型, BeanUtils好处是如果属性是基本数据 类型,BeanUtils会自动帮我转换数据类型。如果设置的属性是其他的引用 类型数据,这时候可以注册一个类型转换器。

1.获得属性的方法:BeanUtils.getProperty(admin,”userName”);

2.设置属性的方法:BeanUtils.setProperty(admin, “id”, 001);

3.拷贝属性的方法:BeanUtils.copyProperty(admin, “usetName”, “peace”);与set效果相同。

4.当属性不能自动转换通过ConvertUtils.register(new Converter())注册转换器;

演示如下:

需要引入包:commons-logging.jar 、 commons-beanutils-1.8.0.jar

Admin中的属性:

private int id;

private String userName;

private String pwd;

private int age;

private Date birth;

BeanUtils使用如下:

public class BeanOpr {

private String name;

@Test

/**

*

*@Title: testHello

*@Description: beanutiils拷贝的介绍

*@return:void

*@throws

*@author peace w_peace@163.com

*/

public void testHello(){

Admin admin=new Admin();

try {

//获得属性方法:

System.out.println(BeanUtils.getProperty(admin,"userName"));

//拷贝属性

BeanUtils.copyProperty(admin, "usetName", "peace");

//类似于设置属性

BeanUtils.setProperty(admin, "id", 001);

//对象的拷贝

Admin admin2=new Admin();

BeanUtils.copyProperties(admin2, admin);

//输出两个admin

System.out.println(admin);

System.out.println(admin2);

//map数据,拷贝到对象中

Map map=new HashMap<>();

map.put("userName","peace2");

map.put("age", 22);

map.put("id", 002);

map.put("pwd", 123456);

//通过Map拷贝:

BeanUtils.populate(admin,map);

System.out.println(admin);

} catch (IllegalAccessException | InvocationTargetException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (NoSuchMethodException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

/**

*

*@Title: testRegist

*@Description: 实现对不支持的类进行转换。

*@return:void

*@throws

*@author peace w_peace@163.com

*/

@Test

public void testRegist(){

// 注册日期类型转换器:1, 自定义的方式

ConvertUtils.register(new Converter() {

/**

* 转换函数,实现对date的转换。

*/

@Override

public Object convert(Class type, Object value) {

//判断是否为Date类型

if(type!=Date.class)

return null;

//判断是否为空

if(value==null||"".equals(value.toString().trim()))

return null;

try {

//转换方式

SimpleDateFormat date=new SimpleDateFormat("yyyy-mm-dd");

return date.parse(value.toString());

} catch (ParseException e) {

throw new RuntimeException(e);

}

}

}, Date.class);

//执行

Admin admin=new Admin();

Map map=new HashMap<>();

map.put("userName","peace2");

map.put("age", 22);

map.put("id", 002);

map.put("pwd", 123456);

map.put("birth", new Date(2015, 10, 9));

try {

BeanUtils.populate(admin,map);

System.out.println(admin);

} catch (IllegalAccessException | InvocationTargetException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

@Test

/**

*

*@Title: testRigest2

*@Description: 使用提供的date类型转换器

*@return:void

*@throws

*@author peace w_peace@163.com

*/

public void testRigest2(){

ConvertUtils.register(new DateConverter(), Date.class);

//执行

Admin admin=new Admin();

Map map=new HashMap<>();

map.put("userName","peace2");

map.put("age", 22);

map.put("id", 002);

map.put("pwd", 123456);

map.put("birth", new Date(2015, 10, 9));

try {

BeanUtils.populate(admin,map);

System.out.println(admin);

} catch (IllegalAccessException | InvocationTargetException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

5.Dbutils数据库JDBC专用工具也可以封装JavaBean:

commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。

下载链接:链接

此去只是简要介绍,后面jdbc教程中在做完整介绍使用如下:

@Test

/**

*

*@Title: testQueryOne

*@Description: 使用组件提供的结果集对象封装数据。

*@return:void

*@throws

*@author peace w_peace@163.com

*/

public void testQueryOne(){

String sql="select * from admin where id=?";

//获取连接

connection=JdbcUtil.getConnection();

//创建Dbutils核心工具类

QueryRunner qr=new QueryRunner();

//查询返回单个对象

try {

//使用beanhandle进行封装

//参数依次为:连接,sql语句,结果处理器,位置参数

//查下你结果封装到Admin

Admin admin=qr.query(connection,sql, new BeanHandler(Admin.class), 4);

System.out.println(admin);

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

try {

connection.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

封装javaBean的方法介绍就到这里.来自一条小鲨鱼wpeace(rlovep.com)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值