Java 对象作为类的成员变量的映射列表 作为一个例子,考虑类A的以下成员变量: Integer id; String name; 现在考虑集合列表对象列表< /C> >值: (0) 1 (1) "Peter"

Java 对象作为类的成员变量的映射列表 作为一个例子,考虑类A的以下成员变量: Integer id; String name; 现在考虑集合列表对象列表< /C> >值: (0) 1 (1) "Peter",java,list,mapping,Java,List,Mapping,是否有(标准)方法将此类对象列表映射到类?我正在为Java对象寻找类似Hibernate的.setResultTransformer(A.class) 注意 import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class ReflectionTestSafe { public static void main(String[] args) { /

是否有(标准)方法将此类对象列表映射到类?我正在为Java对象寻找类似Hibernate的
.setResultTransformer(A.class)

注意

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ReflectionTestSafe {

    public static void main(String[] args) {

        // Map the values to their field name
        Map<String, Object> objMap = new HashMap<String, Object>();
        objMap.put("name", "Peter");
        objMap.put("id", 1);

        // New instasnce of A
        A aInstance = new A();

        // Get all the field of the class
        Field[] aFields = A.class.getDeclaredFields();

        // The number of fields is equal of the number of values?
        if (aFields.length == objMap.size()) {

            for (int index = 0; index < aFields.length; index++) {

                try {

                    // Get the name of the current field (id, name, etc...)
                    String aFieldName = aFields[index].getName();

                    // Check if the field value exist in the map
                    if (!objMap.containsKey(aFieldName)) {
                        throw new Exception("The value of the field " + aFieldName + " isn't mapped!" );
                    }

                    // Get the value from the map based on the field name
                    Object aFieldValue = objMap.get(aFieldName);

                    // Make the private modifier accesible from reflection
                    aFields[index].setAccessible(true);

                    // Set the value of the field
                    aFields[index].set(aInstance, aFieldValue);

                } catch (Exception exception) {
                    // Something went wrong
                    exception.printStackTrace();
                }

            }

        } else {
            System.out.println("Field/Values mismatch");
        }

        // Print the fields of A
        System.out.println(aInstance.toString());

    }

    static class A {

        private Integer id;
        private String name;

        @Override
        public String toString() {
            return "A [id=" + id + ", name=" + name + "]";
        }

    }

}

我知道手动映射总是一种选择,但我的实际类要复杂得多,我正在寻找一种可重用的解决方案

您可以使用以下方法来解决此问题

1) 使用Java从给定类中获取字段计数和字段

2) 将列表的数据填充到属性中


您可以参考此

您可以通过java反射获得结果: 实际上,您可以使用以下方法迭代类的字段:

返回字段对象数组,该数组反映由该类对象表示的类或接口声明的所有字段。这包括公共、受保护、默认(包)访问和私有字段,但不包括继承的字段返回的数组中的元素没有排序,也没有任何特定顺序。如果类或接口未声明任何字段,或者如果此类对象表示基元类型、数组类或void,则此方法返回长度为0的数组

然后按照字段声明的相同顺序从列表中获取值 并分配给他们

旁注:如上所述,类没有特定的顺序。getDeclaredFields()这意味着在不同版本的java上,字段的顺序可能会发生变化,我强烈建议使用一个

不安全代码(参见注释)

import java.lang.reflect.Field;
导入java.util.ArrayList;
导入java.util.List;
公共类反射测试{
公共静态void main(字符串[]args){
//字段值的列表
List objList=new ArrayList();
对象列表添加(1);
对象列表添加(“彼得”);
//新安装
A立场=新的A();
//得到全班所有的场地
字段[]aFields=A.class.getDeclaredFields();
//字段的数量等于值的数量?
if(aFields.length==objList.size()){
for(int index=0;index
(编辑) 安全代码

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ReflectionTestSafe {

    public static void main(String[] args) {

        // Map the values to their field name
        Map<String, Object> objMap = new HashMap<String, Object>();
        objMap.put("name", "Peter");
        objMap.put("id", 1);

        // New instasnce of A
        A aInstance = new A();

        // Get all the field of the class
        Field[] aFields = A.class.getDeclaredFields();

        // The number of fields is equal of the number of values?
        if (aFields.length == objMap.size()) {

            for (int index = 0; index < aFields.length; index++) {

                try {

                    // Get the name of the current field (id, name, etc...)
                    String aFieldName = aFields[index].getName();

                    // Check if the field value exist in the map
                    if (!objMap.containsKey(aFieldName)) {
                        throw new Exception("The value of the field " + aFieldName + " isn't mapped!" );
                    }

                    // Get the value from the map based on the field name
                    Object aFieldValue = objMap.get(aFieldName);

                    // Make the private modifier accesible from reflection
                    aFields[index].setAccessible(true);

                    // Set the value of the field
                    aFields[index].set(aInstance, aFieldValue);

                } catch (Exception exception) {
                    // Something went wrong
                    exception.printStackTrace();
                }

            }

        } else {
            System.out.println("Field/Values mismatch");
        }

        // Print the fields of A
        System.out.println(aInstance.toString());

    }

    static class A {

        private Integer id;
        private String name;

        @Override
        public String toString() {
            return "A [id=" + id + ", name=" + name + "]";
        }

    }

}
import java.lang.reflect.Field;
导入java.util.HashMap;
导入java.util.Map;
公共类ReflectionTestSafe{
公共静态void main(字符串[]args){
//将值映射到它们的字段名
Map objMap=newhashmap();
objMap.put(“姓名”、“彼得”);
objMap.put(“id”,1);
//新安装
A立场=新的A();
//得到全班所有的场地
字段[]aFields=A.class.getDeclaredFields();
//字段的数量等于值的数量?
if(aFields.length==objMap.size()){
for(int index=0;index