简体   繁体   中英

Accessing & determining elements & its type of an object (not array/list) dynamically in java

My common main domain model is flatten kind of and not having list/array for one type of objects.

During the processing I need to put some sort of extraction logic - club all same type of elements in a list/array in some temp object/ model from main model. I don't want to check each elements type manually using getter method call & instance of check since main model is growing, so whenever a new element of existing type is added code need to be updated in extraction logic for the newly added node.

Example - Main Model -

Class MainModel{
 Customer buyer;
 Customer coBuyer;
 Money price;
 ....
}


//Extraction logic in some code which have a populated MainModel object from some service call 
// create a list of <Customer>  Type 
List<Customer> custList = new ArrayList<Customer>();
// populate it without calling getBuyer() and checking its type,

Any idea ?

You can create an interface and put them in the same list without type problem, and in the interface put the method getBuyer()

public Class MainModel implements HasBuyer{
 Customer buyer;
 Customer coBuyer;
 Money price;
 ....
}

public class Customer implements HasBuyer{ ... }

public interface HasBuyer{

 public Customer hasBuyer();

}

after that you could do:

List<HasBuyer> custList = new ArrayList<HasBuyer>();

It sounds like you are needing some reflective code. There are libraries that can also help with this sort of a problem, but a simple method that would do what you are after is as follows.

public class ReflectiveGrabber {
    public static <T> List<T> grabMembers(Class<T> clas, Object object) {
        List<T> list = new ArrayList<>();
        try {
            for (Field field : object.getClass().getDeclaredFields()) {
                if (clas.equals(field.getType())) {
                    field.setAccessible(true);
                    T value = (T) field.get(object);
                    if (value != null) {
                        list.add(value);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void main(String... none) throws Exception {
        System.out.println(grabMembers(String.class, new MainModel("foo", "bah", 10)));
        System.out.println(grabMembers(Integer.class, new MainModel("foo", "bah", 10)));
    }
}

class MainModel {
    MainModel(String buyer, String coBuyer, Integer money) {
        this.buyer = buyer;
        this.coBuyer = coBuyer;
        this.money = money;
    }

    String buyer;
    String coBuyer;
    Integer money;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM