import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
//成员
class Emp {
private String ename;
private String job;
private Double salary;
private java.util.Date hiredate;
private Dept dept = new Dept();
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public java.util.Date getHiredate() {
return hiredate;
}
public void setHiredate(java.util.Date hiredate) {
this.hiredate = hiredate;
}
public String getEname() {
return ename;
}
public void setEname(String name) {
this.ename = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
@Override
public String toString() {
return "Emp [ename=" + ename + ", job=" + job + ", salary=" + salary + ", hiredate=" + hiredate + "]" + "\n" + this.dept;
}
}
//部门
class Dept {
private String dname;
private String loc;
private Long count;
private Company company = new Company();
public Long getCount() {
return count;
}
public void setCount(Long count) {
this.count = count;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
@Override
public String toString() {
return "Dept [dname=" + dname + ", loc=" + loc + ", count=" + count + "]" + "\n" + this.company;
}
}
//公司
class Company {
private Integer cid;
private String name;
private String address;
private java.util.Date create;
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public java.util.Date getCreate() {
return create;
}
public void setCreate(java.util.Date create) {
this.create = create;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String mat() {
SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy-mm-dd");
return DateFormat.format(create);
}
@Override
public String toString() {
return "Company [cid=" + cid + ", name=" + name + ", address=" + address + ", create=" + mat() + "]";
}
}
/*
* 1、实例化成员类
* 2、设置成员属性
* 3、获取成员类
*/
class EmpAction {
Emp emp = new Emp(); //实例化成员
// 设置成员属性
public void setValue(String value) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, NoSuchFieldException, ParseException, InstantiationException {
BeanOperation.setBeanValue(this,value);
}
public Emp getEmp() {
return emp;
}
public Emp setEmp() {
return emp;
}
}
//字符串解析
class BeanOperation {
private BeanOperation() {}
public static void setBeanValue(Object actionObject,String msg) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, NoSuchFieldException, ParseException, InstantiationException {
String[] result = msg.split("\\|"); //不同成员变量间分隔
for(int x = 0; x < result.length; x ++) {
String[] temp = result[x].split(":"); //名称和值的分隔
String attribute = temp[0]; //类名和成员属性名
String value = temp[1]; //不同类型属性值
String[] fields = attribute.split("\\."); //级层数组
int i = fields.length-1; //最高层级层脚标
Object currentObject = actionObject;
for(int y = 0; y < i; y ++) {
// 通过反射在actionObject类中查找成员fields[y],返回被实例化的成员类
currentObject = ObjectUtils.getObject(currentObject,fields[y]);//第一次返回emp
}
//操作类,属性类型,属性值 属性类型field.getType()
ObjectUtils.setObjectValue(currentObject, fields[i], value);
// emp.dept.company fields[0++] (actionObject = currentObject,fields[0++])
}
}
}
//参数值类型处理
class ObjectValueUtils{
private ObjectValueUtils() {}
/**
*
* @param 被操作的类
* @param 属性类型
* @param 属性值
* @return 被转类型换后的值
* @throws ParseException
*/
public static Object getValue(String type,Object value) throws ParseException {
return stringToType(type,value);
}
// 字符串为空时返回false
private static boolean isNotEmpty(String type) {
return !(type == null || type.isEmpty() || "".equals(type));
}
// 字符串
private static boolean isString(String type) {
if(isNotEmpty(type)) {
if("String".equals(type)) {
return true;
} else {
return false;
}
}
return false;
}
// 整型
private static boolean isInt(String type) {
if(isNotEmpty(type)) {
if("Int".equals(type) || "Integer".equals(type)) {
return true;
} else {
return false;
}
}
return false;
}
// 长整型
private static boolean isLong(String type) {
if(isNotEmpty(type)) {
if("Long".equals(type) || "long".equals(type)) {
return true;
} else {
return false;
}
}
return false;
}
// 单双精度
private static boolean isDouble(String type) {
if(isNotEmpty(type)) {
if("double".equals(type) || "Double".equals(type)) {
return true;
} else {
return false;
}
}
return false;
}
// 日期
private static boolean isDate(String type) {
if("Date".equals(type)) {
return true;
} else {
return false;
}
}
// 字符串转型处理
public static Object stringToType(String type,Object value) throws ParseException {
if(isString(type)) {
return value;
}
if(isInt(type)) {
return Integer.parseInt((String) value);
}
if(isLong(type)) {
return Long.parseLong((String) value);
}
if(isDouble(type)) {
return Double.parseDouble((String) value);
}
if(isDate(type)) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
return formatter.parse((String) value);
}
return null; //不符合所有类型
}
}
//字符串处理
class StringUtils {
private StringUtils() {}
public static String initcap(String str) {
return str.substring(0,1).toUpperCase() + str.substring(1); //首字母大写+剩余字符串
}
}
/*
* 1、通过反射获取类中的成员变量并检查是否存在子类中以便后续的赋值
* 2、通过反射获取类中的指定方法并调用该方法返回被实例化的类的对象
*/
class ObjectUtils {
private ObjectUtils() {}
// 获取类属性
public static Object getObject(Object wrapObject,String attribute) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, NoSuchFieldException, InstantiationException, ParseException {
String methodName = "get" + StringUtils.initcap(attribute); //调用字符串大小写处理方法获得"getter方法名"字符串
Field field = wrapObject.getClass().getDeclaredField(attribute); //通过反射取得指定类中指定成员变量
if(field == null) { //如果成员变量中没有找到,可能是父类中的属性
field = wrapObject.getClass().getField(attribute);
}
if(field == null) { //类中不存在该属性,确认为Null
return null;
}
Method method = wrapObject.getClass().getMethod(methodName); //通过反射获取指定类中的指定方法
Object obj = method.invoke(wrapObject);
return method.invoke(wrapObject); //调用无参方法
}
// 设置成员变量(参数:当前类,类属性名称,属性值)
public static void setObjectValue(Object wrapObject,String attribute,Object value) throws NoSuchFieldException, SecurityException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ParseException {
Field field = wrapObject.getClass().getDeclaredField(attribute); //field为当前类中的属性名称
if(field == null) { //类中没有找到属性值,可能是父类中的属性
field = wrapObject.getClass().getField(attribute);
}
if(field == null) { //类中不存在该属性,确认为Null
return ;
}
String methodName = "set" + StringUtils.initcap(attribute);
Method method = wrapObject.getClass().getMethod(methodName,field.getType()); //method = 方法(参数类型)
//调用有参方法
method.invoke(wrapObject,ObjectValueUtils.getValue(field.getType().getSimpleName(), value)); //例:(类,属性类型,参数)
}
}
/*计算结果:
* Emp [ename=康康, job=clerk, salary=3.14, hiredate=null]
* Dept [dname=财务部, loc=良好, count=null]
* Company [cid=null, name=null, address=北京, create=2018-02-06]
*/
public class Test {
public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, NoSuchFieldException, ParseException, InstantiationException {
String value = "emp.ename:康康|emp.job:clerk|emp.salary:3.14|emp.dept.dname:财务部|emp.dept.loc:良好|emp.dept.company.create:2018-02-06|emp.dept.company.address:北京";
EmpAction action = new EmpAction();
action.setValue(value); //传入字符串参数设置并获取相应成员类属性的值
System.out.println(action.getEmp());
}
}
java多类型反射雏形
最新推荐文章于 2021-02-27 09:43:28 发布