2017-01-31 8 views
2

В качестве примера, рассмотрим класс A со следующими переменными-членами:список Отображение объектов в качестве переменных-членов класса

Integer id; 
String name; 

Теперь рассмотрим коллекцию List<Object> objList со значениями:

(0) 1 
(1) "Peter" 

Есть (стандартный) способ сопоставления такого списка объектов с классом? Я ищу что-то вроде Hibernate's .setResultTransformer(A.class) для объектов Java.

ПРИМЕЧАНИЕ

Я знаю, ручное отображение всегда является вариант, но мой фактический класс является гораздо более сложным, и я ищу для многократного использования раствора.

ответ

1

вы можете достичь результата с Java Reflection: по существу итерации по полям класса с го Способ е: Class.getDeclaredFields()

Возвращает массив объектов Field, отражающие все поля, объявленные класс или интерфейс, представленный этот объект класса. Это включает открытый, защищенный, доступ по умолчанию (пакетный) и частные поля, но исключает унаследованные поля. Элементы возвращенного массива не сортируются и не находятся в определенном порядке. Этот метод возвращает массив длины 0, если класс или интерфейс не объявляет никаких полей, или если этот объект класса представляет примитивный тип, класс массива или void.

Затем вы получите значения из списка в том же порядке, что и объявление полей , и назначьте их.

Примечание стороны: как уже упоминалось выше, не существует определенный порядок Class.getDeclaredFields() это означает, что порядок полей может измениться на другую версию Java, я настоятельно советую отобразить значения их имя поля с Map(см безопасный код)

небезопасный код(см примечание)

import java.lang.reflect.Field; 
import java.util.ArrayList; 
import java.util.List; 

public class ReflectionTest { 

    public static void main(String[] args) { 

     // List of the fields values 
     List<Object> objList = new ArrayList<Object>(); 
     objList.add(1); 
     objList.add("Peter"); 

     // 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 == objList.size()) { 

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

       try { 

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

        // Set the value of the field based on the value of the list 
        aFields[index].set(aInstance, objList.get(index)); 

       } 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 + "]"; 
     }  

    } 

} 

(редактировать) SAFE КОД

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 + "]"; 
     } 

    } 

} 
0

Вы можете использовать ниже подхода решить проблему

1) С помощью Java reflection, чтобы получить количество поля и поля из данного класса

2) Заполняем данные для списка свойств

вы можете передать этот link

 Смежные вопросы

  • Нет связанных вопросов^_^