如何从父对象创建子对象并分配一些字段

问题描述 投票:0回答:1

我是Java新手,想收集一些想法,因为我陷入困境。

我有一些家长班,比如说

@Data
public class Person implements Hometown {
    private String name;
    private Country motherland;
}

界面:

public interface Hometown {     
    Country getMotherland(); 
}

还有一些儿童课程:

@Data
public class Norwegian extends Person {  
    //motherland should be "Norway"
    ..
}

@Data
public class Portuguese extends Person {
    //motherland should be "Portugal"  
    ..
}

通过 RestClient 我可以接收 Person 类:

public interface PopulationInfoClient {

    @GET
    @Path("/people/{personId}")
    Person search(@PathParam("personId") String personId);

}

收到个人信息后,我想将他们设置为我服务的家乡。然后返回一个泛型类型的子类(可以是挪威语、葡萄牙语等)。

@Inject
@RestClient
PopulationInfoClient populationInfoClient;

public T getCitizen(String personId) {
    Person person = this.populationInfoClient.search(personId);
    ...
    return ...
}

问题是如何使用泛型创建像 Norwegien 这样的子类,并将祖国设置为“挪威”?并在我的服务函数 getCitizen() 中返回它们?

我将感谢您的答案和想法

我尝试使用工厂模式,但失败了

java generics inheritance factory-pattern
1个回答
0
投票

嗯,我认为你可以使用通用工厂方法。

接口:

public interface PersonFactory<T extends Person> {
    T create(String nationality);
}

实施:

public class NorwegianFactory implements PersonFactory<Norwegian> {
    @Override
    public Norwegian create(String nationality) {
        Norwegian norwegian = new Norwegian();
        norwegian.setMotherland(Country.NORWAY);
        return norwegian;
    }
}

您更新的代码:

@Inject
@RestClient
PopulationInfoClient populationInfoClient;

@Inject
private Map<String, PersonFactory> personFactories;

public T getCitizen(String personId) {
    Person person = this.populationInfoClient.search(personId);
    String nationality = person.getNationality();

    PersonFactory<T> personFactory = personFactories.get(nationality);
    if (personFactory == null) {
        throw new IllegalArgumentException("Unknown nationality is " + nationality);
    }

    return personFactory.create(nationality);
}
© www.soinside.com 2019 - 2024. All rights reserved.