mercredi 13 mai 2020

How can we determine object type class while creating dynamic conditional class in java

I have factory class to create object based on my conditional term, but i unable to create it because i need to declare which class i want to use meanwhile the class i use based on my rule condition. How to solve this?

CustomerFactory.class

public class CustomerFactory {

    public CustomerBuyer getType(String type) {
        if(type == "buyer") {
            CustomerBuyer<DataDetailBuy> myCustomer = new CustomerBuyer();
            myCustomer.setName("buyer1");
            myCustomer.getDataDetail().setItemCode("ITEM001");
            return myCustomer;
        }else if(type == "seller"){
            CustomerBuyer<DataDetailSell> myCustomer = new CustomerBuyer();
            return myCustomer;
        }       


    }
}

CustomerBuyer.class

public class CustomerBuyer<T> {

    public String name;
    public T dataDetail;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public T getDataDetail() {
        return dataDetail;
    }
    public void setDataDetail(T dataDetail) {
        this.dataDetail = dataDetail;
    }


}

App.java

public class App {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        CustomerFactory customerFactory = new CustomerFactory();

        CustomerBuyer person1 = customerFactory.getType("buyer");

        person1.getName();
        person1.getDataDetail();

        CustomerBuyer person2 = customerFactory.getType("seller");

        person2.getName();
        person2.getDataDetail().getProfit();

    }

}

The function getType on CustomerFactory has error, because the return class type is dynamic. How to tell the function to accept return dynamic type class based on my condition? On the other side the class type is chosen while in runtime

Note: <T> generic class i want to assign with different class each condition

Aucun commentaire:

Enregistrer un commentaire