You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将多个相似的Person子类处理方法优化为单一泛型函数?

问题描述

我有多个继承自Person类型的子类对象,针对每种Person子类都有相似的处理方法,唯一区别在于子类类型。例如:

public void handlePerson1(final String request) {
    PersonExample<Person1> personExample = new PersonExample<>(Person1.class);
    OtherPersonExample<Person1> otherPersonExample = new OtherPersonExample<>(Person1.class);
    // 其他针对Person1的处理逻辑
}

public void handlePerson2(final String request) {
    PersonExample<Person2> personExample = new PersonExample<>(Person2.class);
    OtherPersonExample<Person2> otherPersonExample = new OtherPersonExample<>(Person2.class);
    // 其他针对Person2的处理逻辑
}

我曾尝试让主类继承泛型类型,以便按需初始化相关类(类似已实现的PersonExample泛型类):

public class PersonExample<T extends Person> {
    private final Class<T> classType;

    // 获取Class类型
    public PersonExample(final Class<T> classType) {
        this.classType = classType;
    }

    public void handleFunction(Something<T> something) {
        // SOMETHING可以是Person1、Person2等类型实例
    }
}

请问能否帮我将handlePerson1、handlePerson2等方法合并为一个单一函数?

解决方案

当然可以,你可以通过泛型方法来实现,将子类的Class对象作为参数传入,这样一个方法就能处理所有Person的子类:

// 泛型方法,T限定为Person的子类
public <T extends Person> void handlePerson(final String request, Class<T> personClass) {
    PersonExample<T> personExample = new PersonExample<>(personClass);
    OtherPersonExample<T> otherPersonExample = new OtherPersonExample<>(personClass);
    
    // 这里编写通用的处理逻辑,后续无论新增多少Person子类,都无需修改此方法
}

调用示例

// 处理Person1类型
handlePerson(request, Person1.class);
// 处理Person2类型
handlePerson(request, Person2.class);

这种方式不仅减少了重复代码,还符合开闭原则——后续新增Person子类时,只需要传入对应的Class对象即可,无需新增处理方法。

内容的提问来源于stack exchange,提问作者Renato Quelhas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 11:02:25