我是Java 的新手,我想收集一些 idea ,因为我搞砸了.

我有一些家长班,比方说

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

一个接口:

public interface Hometown {     
    Country getMotherland(); 
}

以及一些 children 班级:

@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 ...
}

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

如果能给我答案和 idea ,我将不胜感激

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

推荐答案

我认为您可以使用定制的泛型工厂方法.

接口:

public interface PersonFactory<T extends Person> {
    T create(Person person, Country motherland);
}

实施:

public class NorwegianFactory implements PersonFactory<Norwegian> {
    
    @Override
    public Norwegian create(Person person, Country motherland) {
        Norwegian norwegian = new Norwegian();
        norwegian.setName(person.getName());
        norwegian.setMotherland(motherland);
        return norwegian;
    }
}

您的更新代码:

@Inject
@RestClient
PopulationInfoClient populationInfoClient;

@Inject
private Map<String, PersonFactory> personFactories;

public T getCitizen(String personId, Country motherland) {
    Person person = this.populationInfoClient.search(personId);

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

    return personFactory.create(person, motherland);
}

Java相关问答推荐

try Dockerize Maven应用程序,但发布版本21不支持"

Mongo DB Bson和Java:在子文档中添加和返回仅存在于父文档中的字段?

当切换javaFX场景时,stage的大小正在Minimize

Java:根据4象限中添加的行数均匀分布行的公式

springboot start loge change

有没有一种方法使保持活动设置专用于java.net.http.HttpClient的一个实例

SpringBootreact 式Web应用程序的Spring Cloud Configer服务器中的资源控制器损坏

匹配一组字符或另一组字符

Sack()步骤中的合并运算符未按预期工作

解析方法";javax/imageio/metadata/IIOMetadata.getAsTree(Ljava/lang/String;)Lorg/w3c/dom/Node时加载约束冲突

将JSON字符串转换为Java类

Instancio未在日志(log)中显示测试失败消息

当b是一个字节并且在Java中值为-1时,为什么b>;>;>;1总是等于-1?

IntelliJ IDEA中的JavaFX应用程序无法在资源中找到CSS文件

为了安全起见,有必要复制一份 list 吗?

Java KeyListener不工作或被添加

不能在 map 上移除折线

让标签占用JavaFX中HBox的所有可用空间

java.lang.NoSuchMethodError:';org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream$Builder org.apache.poi-poi-ooxml-5.2.4

Android上的SQLite:Android.database.SQLite.SQLiteReadOnlyDatabaseException:try 写入只读数据库(代码1032 SQLite_readonly_DBMOVED)