• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

java实现两个对象内容的交换

error 来源:maguangkun 5次浏览
package com.mgk.test1.three;

import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class Test {
    private Field[] newField;
    private Object[] objects;
    public static void main(String[] args) {
        Student oldStudent = new Student("oldId","oldName","oldAge","oldSex");
        Student newStudent = new Student("newId","newName","newAge","newSex");
        System.out.println("更改之前旧的"+oldStudent.toString());
        String s = new Test().oldAndNewReplace(oldStudent, newStudent,"id","name");
        System.out.println("旧的------------"+oldStudent.toString());
    }
    /**
     * 判断该字段是否包含该数组中
     */
    private boolean containsArr(String str){
        if(objects == null){
            return  false;
        }
        for (Object obj:objects) {
            if(obj.equals(str)){
                return true;
            }
        }
        return false;
    }
    /**
     *  新旧程序替换
     *  将第二个参数值复制到第一个参数值中
     * @param oldObj
     * @param newObj
     */
    private  String  oldAndNewReplace(Object oldObj ,Object newObj) {
        Class<?> oldClass = oldObj.getClass();
        Class<?> newClass = newObj.getClass();
        if (!oldClass.getSimpleName().equals(newClass.getSimpleName())){
            return "两个对象不一致";
        }
        newField = newClass.getDeclaredFields();
        for (Field field: newField) {
            Method newMethod = null;
            Method oldmethod =null;
            try {
                if(containsArr(field.getName())) {
                    continue;
                 }
                    newMethod = newClass.getMethod("get" + getDx(field.getName()));
                    Object invoke = newMethod.invoke(newObj);
                    oldmethod = oldClass.getMethod("set" + getDx(field.getName()), field.getType());
                    oldmethod.invoke(oldObj, invoke);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "success";
    }
    /**
     *
     *  新旧程序替换
     *  将第二个参数值复制到第一个参数值中
     * @param oldObj
     * @param newObj
     * @param objects 属性名称不需要替换的属性名称
     * @return
     */
    private  String  oldAndNewReplace(Object oldObj ,Object newObj,Object ... objects) {
        this.objects = objects;
        return  this.oldAndNewReplace(oldObj,newObj);
    }

    /**
     * 首字母转大写
     * @param str
     * @return
     */
    private String getDx(String str){
        char[] chars = str.toCharArray();
        if (chars[0] >= 'a' && chars[0] <= 'z') {
            chars[0] = (char)(chars[0] - 32);
            return new String(chars);
        }
        return "error";
    }
}
class Student{
    private String id;
    private String name;
    private String age;
    private String sex;
    public Student() {
    }
    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
    public Student(String id, String name, String age, String sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

 

重新改进一部分,跟上面无关联

package com.mgk.test1.four;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public interface  ObjectUtilInterface {
    /**
     * 拿到对象的get方法
     * @return
     */
    Method getObjMethod(String name, int state ,Class<?>... parameterTypes) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException;
    /**
     * 调用方法
     * @return
     */
    Object invokeMethod(int state ,Object... parameterTypes) throws InvocationTargetException, IllegalAccessException;

    /**
     * 实现
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    String oldAndNewBegin() throws InvocationTargetException, IllegalAccessException;
}
package com.mgk.test1.four;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public abstract class AbstractObjectUtil implements ObjectUtilInterface{
    private Object[] objects;
    private Object obj1;
    private Object obj2;
    public AbstractObjectUtil(Object obj1, Object obj2) {
        this.obj1 = obj1;
        this.obj2 = obj2;
        if(!obj1.getClass().getSimpleName().equals(obj2.getClass().getSimpleName())){
            throw(new RuntimeException("两个参数不属于一个模型不可以数据交互"));
        }
    }
    public AbstractObjectUtil(Object obj1, Object obj2,Object ... objects) {
        this(obj1,obj2);
        this.objects = objects;
    }

    /**
     * 是否包含
     */
     boolean containsArr(String str) {
        if(objects == null){
            return  false;
        }
        for (Object obj:objects) {
            if(obj.equals(str)){
                return true;
            }
        }
        return false;
    }
    /**
     * 首字母转大写
     * @param str
     * @return
     */
    public String getDx(String str){
        char[] chars = str.toCharArray();
        if (chars[0] >= 'a' && chars[0] <= 'z') {
            chars[0] = (char)(chars[0] - 32);
            return new String(chars);
        }
        throw(new RuntimeException("首字母转大写失败("+str+"):字段不在a-z之间"));
    }
}
package com.mgk.test1.four;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class DefaultObjectUtil extends AbstractObjectUtil{
    private final int obj1State = 0;//代表取的第一个对象的参数
    private final int obj2State = 1;//代表取的第二个对象的参数
    private Field[] newField;
    private Object oldObj;
    private Object newObj;
    private Class<?> oldClass ;
    private Class<?> newClass ;
    private Method oldMethod =null;
    private Method newMethod = null;
    public DefaultObjectUtil(Object obj1, Object obj2,Object ... objects) {
        super(obj1, obj2,objects);
        this.oldObj = obj1;
        this.newObj = obj2;
        oldClass = oldObj.getClass();
        newClass = newObj.getClass();
    }
    public DefaultObjectUtil(Object obj1, Object obj2) {
        this(obj1, obj2,"");
    }
    /**
     *  新旧程序替换
     */
    @Override
    public   String  oldAndNewBegin() {
        newField = newClass.getDeclaredFields();
        for (Field field: newField) {
            try {
                if(containsArr(field.getName())) {
                    continue;
                }
                getObjMethod("get" + getDx(field.getName()),this.obj2State);
                Object invoke = invokeMethod(this.obj2State);
                getObjMethod("set" + getDx(field.getName()),this.obj1State, field.getType());
                invokeMethod(this.obj1State, invoke);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "success";
    }
    @Override
    public Method getObjMethod(String name,int state ,Class<?>... parameterTypes) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method tempMethod = null;
        if (state==0){
            oldMethod= oldClass.getMethod(name,parameterTypes);
        }else {
            newMethod= newClass.getMethod(name,parameterTypes);
        }
        return tempMethod;
    }
    @Override
    public Object invokeMethod(int state, Object... parameterTypes) throws InvocationTargetException, IllegalAccessException {
        Object tempObj;
        if (state==0){
            tempObj = oldMethod.invoke(oldObj, parameterTypes);
        }else {
            tempObj = newMethod.invoke(newObj, parameterTypes);
        }
        return tempObj;
    }

    public int getObj1State() {
        return obj1State;
    }

    public int getObj2State() {
        return obj2State;
    }

    public Field[] getNewField() {
        return newField;
    }

    public Object getOldObj() {
        return oldObj;
    }

    public Object getNewObj() {
        return newObj;
    }

    public Class<?> getOldClass() {
        return oldClass;
    }

    public Class<?> getNewClass() {
        return newClass;
    }

    public Method getOldMethod() {
        return oldMethod;
    }

    public Method getNewMethod() {
        return newMethod;
    }
}
package com.mgk.test1.four;

import java.lang.reflect.Field;

public class AddObjectUtil extends DefaultObjectUtil{
    public AddObjectUtil(Object obj1, Object obj2, Object... objects) {
        super(obj1, obj2, objects);
    }
    public AddObjectUtil(Object obj1, Object obj2) {
        super(obj1, obj2);
    }
    /**
     * 需求1.追加字段
     * @return
     */
    @Override
    public String oldAndNewBegin() {
        Field[] newField = getNewClass().getDeclaredFields();
        for (Field field: newField) {
            try {
                if(containsArr(field.getName())) {
                    continue;
                }
                //新数据
               getObjMethod("get" + getDx(field.getName()),getObj2State());
                Object invoke = invokeMethod(getObj2State());
                //原有数据
                getObjMethod("get" + getDx(field.getName()),getObj1State());
                Object invoke1 = invokeMethod(getObj1State());

                getObjMethod("set" + getDx(field.getName()),getObj1State(), field.getType());
                invokeMethod(getObj1State(), invoke1.toString()+invoke);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "success";
    }
}

设计有很多缺陷目前能想到的这就些希望大佬多多指点。

//重新增加一部分和上面无关

1.增加非相同对象可以Copy到旧对象的值

package com.example.rbac.util;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

    public class Test {
        private String[][] objects;
        public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
            Student oldStudent = new Student("oldId","oldName","oldAge","oldSex");
            dog newStudent = new dog();
            String[][] problemArr={
                    {"id","dogId"},
                    {"name","dogName"},
                    {"age","dogAge"},
//                    {"sex","dogSex"},
            };
            System.out.println("更改之前新的"+oldStudent.toString());
            String s = new Test().oldAndNewReplace(oldStudent, newStudent,problemArr);
            System.out.println("新的------------"+newStudent.toString());
            //arr();
        }

        /**
         * 测试二维数组
         */
        public static void arr(){
            String[][] str = new String[3][2];
            str[0][0]= "1";
            str[0][1]= "2";
//            str[1][0]= "1";
//            str[1][1]= "2";
            System.out.println(str[0].length);
        }



        /**
         * 判断该字段是否包含该数组中
         */
        private boolean containsArr(String str){
            if(objects == null){
                return  false;
            }
            for (Object obj:objects) {
                if(obj.equals(str)){
                    return true;
                }
            }
            return false;
        }
        /**
         *  新旧程序替换
         *  将第二个参数值复制到第一个参数值中
         * @param oldObj
         * @param newObj
         */
        private  String  oldAndNewReplace(Object oldObj ,Object newObj) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
            Class<?> oldClass = oldObj.getClass();
            Class<?> newClass = newObj.getClass();
//            if (!oldClass.getSimpleName().equals(newClass.getSimpleName())){
//                return "两个对象不一致";
//            }

            for (String[] field: objects) {
                Method newMethod = null;
                Method oldmethod =null;
                oldmethod = oldClass.getMethod("get" + getDx(field[0]));
                Object invoke = oldmethod.invoke(oldObj);
                newMethod = newClass.getMethod("set" + getDx(field[1]),String.class);
                newMethod.invoke(newObj, invoke);
            }
            return "success";
        }
        /**
         *
         *  新旧程序替换
         *  将第二个参数值复制到第一个参数值中
         * @param oldObj
         * @param newObj
         * @param objects 属性名称不需要替换的属性名称
         * @return
         */
        private  String  oldAndNewReplace(Object oldObj ,Object newObj,String[][] objects) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
            this.objects = objects;
            return  this.oldAndNewReplace(oldObj,newObj);
        }

        /**
         * 首字母转大写
         * @param str
         * @return
         */
        private String getDx(String str){
            char[] chars = str.toCharArray();
            if (chars[0] >= 'a' && chars[0] <= 'z') {
                chars[0] = (char)(chars[0] - 32);
                return new String(chars);
            }
            return "error";
        }
    }
    class Student{
        private String id;
        private String name;
        private String age;
        private String sex;
        public Student() {
        }
        @Override
        public String toString() {
            return "Student{" +
                    "id='" + id + '\'' +
                    ", name='" + name + '\'' +
                    ", age='" + age + '\'' +
                    ", sex='" + sex + '\'' +
                    '}';
        }
        public Student(String id, String name, String age, String sex) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.sex = sex;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getAge() {
            return age;
        }

        public void setAge(String age) {
            this.age = age;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }
    }
    class dog{
        public dog() {
        }

        private String dogId;
        private String dogName;
        private String dogSex;
        private String dogAge;

        public dog(String dogId, String dogName, String dogSex, String dogAge) {
            this.dogId = dogId;
            this.dogName = dogName;
            this.dogSex = dogSex;
            this.dogAge = dogAge;
        }

        @Override
        public String toString() {
            return "dog{" +
                    "dogId='" + dogId + '\'' +
                    ", dogName='" + dogName + '\'' +
                    ", dogSex='" + dogSex + '\'' +
                    ", dogAge='" + dogAge + '\'' +
                    '}';
        }

        public String getDogId() {
            return dogId;
        }

        public void setDogId(String dogId) {
            this.dogId = dogId;
        }

        public String getDogName() {
            return dogName;
        }

        public void setDogName(String dogName) {
            this.dogName = dogName;
        }

        public String getDogSex() {
            return dogSex;
        }

        public void setDogSex(String dogSex) {
            this.dogSex = dogSex;
        }

        public String getDogAge() {
            return dogAge;
        }

        public void setDogAge(String dogAge) {
            this.dogAge = dogAge;
        }
    }

 

 


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)