java 反射get set_java反射执行pojo中的set/get方法 | 学步园

1、pojo类

package net.gtja.ldap;

public class Dept {

private String ldapUserName ;

private String userName ;

private String phoneNum ;

private String email ;

private int deviceNum ;

private int groupId ;

private String groupName ;

private String groupLevel ;

private int parentGroupID ;

public String getLdapUserName() {

return ldapUserName;

}

public void setLdapUserName(String ldapUserName) {

this.ldapUserName = ldapUserName;

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

public String getPhoneNum() {

return phoneNum;

}

public void setPhoneNum(String phoneNum) {

this.phoneNum = phoneNum;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public int getDeviceNum() {

return deviceNum;

}

public void setDeviceNum(int deviceNum) {

this.deviceNum = deviceNum;

}

public int getGroupId() {

return groupId;

}

public void setGroupId(int groupId) {

this.groupId = groupId;

}

public String getGroupName() {

return groupName;

}

public void setGroupName(String groupName) {

this.groupName = groupName;

}

public String getGroupLevel() {

return groupLevel;

}

public void setGroupLevel(String groupLevel) {

this.groupLevel = groupLevel;

}

public int getParentGroupID() {

return parentGroupID;

}

public void setParentGroupID(int parentGroupID) {

this.parentGroupID = parentGroupID;

}

}

2、通过反射执行Dept中的所有get方法

package net.gtja.ldap;

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

public class T {

/**

* @param args

* @throws NoSuchMethodException

* @throws SecurityException

* @throws InvocationTargetException

* @throws IllegalAccessException

* @throws IllegalArgumentException

* @throws InstantiationException

*/

public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException {

Class> clazz = Dept.class ;

// 取得所有属性,不包括父类的属性

Field[] fields = clazz.getDeclaredFields() ;

for (int i = 0; i < fields.length; i++) {

// 迭代每一个属性

String field = fields[i].getName() ;

// 拼装出get方法名

String methodName = "get"+String.valueOf(field.charAt(0)).toUpperCase()+field.substring(1) ;

// 通过方法名取得方法对象

Method m = clazz.getMethod(methodName) ;

// m.invoke(obj)传入的是该方法所在类的实例

System.out.println(m.invoke(clazz.newInstance()));

}

}

}

二、java中通过reflect,Introspector,PropertyDescriptor执行setter/getter方法比较

1、反射执行方法

package com.akwolf.bean;

import java.lang.reflect.Method;

/**

* 通过反射获取一个方法并执行

*

* 这样必须清楚的知道一个类中的方法,才好进行调用

*

* 文件名 : ReflectInvoke.java

* @version : 1.0

* @author : zhangh

* @email : zhangh@justsy.com

* @create date : 2012-9-21

*/

public class ReflectInvoke {

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

Class> clazz = Class.forName("com.akwolf.bean.Student") ;

Method readName = clazz.getDeclaredMethod("getName") ;

Method writeName = clazz.getDeclaredMethod("setName",String.class) ;

Object obj = clazz.newInstance() ;

writeName.invoke(obj, "zhangh") ;

Object o = readName.invoke(obj) ;

System.out.println(o);

}

}

2、Introspector执行方法

package com.akwolf.bean;

import java.beans.BeanInfo;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.lang.reflect.Method;

/**

* 通过Introspector类获取bean类的所有缺省setter/getter方法

*

* 这样做可以遍历所有的方法,与PropertyDescriptor类似,但没有那个方便

*

*

* 文件名 : IntrospectorInvoke.java

* @version : 1.0

* @author : zhangh

* @email : zhangh@justsy.com

* @create date : 2012-9-21

*/

public class IntrospectorInvoke {

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

Class> clazz = Class.forName("com.akwolf.bean.Student");

BeanInfo beanInfo = Introspector.getBeanInfo(clazz, Object.class);

PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors() ;

for (PropertyDescriptor propertyDescriptor : pds) {

if("name".equals(propertyDescriptor.getName())){

Method readName = propertyDescriptor.getReadMethod();

Method writeName = propertyDescriptor.getWriteMethod() ;

Object obj = clazz.newInstance() ;

writeName.invoke(obj, "zhangh") ;

Object o = readName.invoke(obj) ;

System.out.println(o);

}

}

}

}

3、PropertyDescriptor执行方法

package com.akwolf.bean;

import java.beans.PropertyDescriptor;

import java.lang.reflect.Method;

/**

* 通过PropertyDescriptor类,通过传入一个属性值获取标准的setter/getter方法进行

* 调用,简单方便

*

* 文件名 : PropertyDescriptorInvoke.java

* @version : 1.0

* @author : zhangh

* @email : zhangh@justsy.com

* @create date : 2012-9-21

*/

public class PropertyDescriptorInvoke {

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

Class> clazz = Class.forName("com.akwolf.bean.Student") ;

PropertyDescriptor pd = new PropertyDescriptor("name", clazz) ;

Method readName = pd.getReadMethod() ;

Method writeName = pd.getWriteMethod() ;

Object obj = clazz.newInstance() ;

writeName.invoke(obj, "zhangh") ;

Object o = readName.invoke(obj) ;

System.out.println(o);

}

}

package com.akwolf.bean;

public class Student {

private int id;

private String name;

private int age;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

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;

}

}

嗲用方法时类型的转换

package common.db;

import java.beans.BeanInfo;

import java.beans.IntrospectionException;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.sql.Connection;

import java.sql.SQLException;

import java.util.Iterator;

import java.util.Properties;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import com.mchange.v2.c3p0.DataSources;

public final class ConnectionManager {

private static ConnectionManager instance;

public ComboPooledDataSource ds;

private static String c3p0Properties = "c3p0.properties";

private ConnectionManager() throws Exception {

Properties p = new Properties();

p.load(ConnectionManager.class.getClassLoader().getResourceAsStream(

c3p0Properties));

ds = new ComboPooledDataSource();

setDataSourceValue(ds, p);

}

private Object getRealType(Class> field, String value) {

Object obj = value;

if (field.equals(String.class)) {

obj = value.toString();

} else if (field.equals(Integer.class) || field.equals(int.class)) {

obj = Integer.parseInt(value);

} else if (field.equals(Float.class) || field.equals(float.class)) {

obj = Float.parseFloat(value);

} else if (field.equals(Double.class) || field.equals(double.class)) {

obj = Double.parseDouble(value);

} else if (field.equals(Long.class) || field.equals(long.class)) {

obj = Long.parseLong(value);

} else if (field.equals(Short.class) || field.equals(short.class)) {

obj = Short.parseShort(value);

} else if (field.equals(Boolean.class) || field.equals(boolean.class)) {

obj = Boolean.parseBoolean(value);

}

return obj;

}

private void setDataSourceValue(ComboPooledDataSource ds, Properties p)

throws SecurityException, NoSuchMethodException,

IllegalArgumentException, IllegalAccessException,

InvocationTargetException, IntrospectionException {

Iterator keys = p.keySet().iterator();

BeanInfo beanInfo = Introspector

.getBeanInfo(ComboPooledDataSource.class);

PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();

while (keys.hasNext()) {

String key = (String) keys.next();

for (int i = 0; i < pds.length; i++) {

String propertyName = pds[i].getName();

if (key.equals(propertyName)) {

String value = p.getProperty(key);

Class> propertyType = pds[i].getPropertyType();

Object val = getRealType(propertyType, value);

Method method = pds[i].getWriteMethod();

System.out.println(method.getName() + "----" + key + "---"

+ value);

method.invoke(ds, new Object[] { val });

}

}

}

}

public static final ConnectionManager getInstance() {

if (instance == null) {

try {

instance = new ConnectionManager();

} catch (Exception e) {

e.printStackTrace();

}

}

return instance;

}

public synchronized final Connection getConnection() {

try {

return ds.getConnection();

} catch (SQLException e) {

e.printStackTrace();

}

return null;

}

protected void finalize() throws Throwable {

DataSources.destroy(ds); // 关闭datasource

super.finalize();

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值