有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何从java中的PersonRepo中删除泛型?

我试图创建一个库类,用于在java中执行事务。下面是代码示例

class AbstractRepo {
    <T extends AbstractRepo> void transactional(Consumer<T> consumer) {
        System.out.println("Transaction started.");
        consumer.accept((T) this); //try-catch removed for brevity
        System.out.println("Transaction finished.");
    }
}

class PersonRepo extends AbstractRepo {
    void addPerson() {
        System.out.println("Adding person.");
    }

    void addAddress() {
        System.out.println("Adding address.");
    }
}

public class Application {
    public static void main(String[] args) {
        var personRepo = new PersonRepo();
        personRepo.<PersonRepo>transactional(it -> {
            it.addPerson();
            it.addAddress();
        });
    }
}

每当PersonRepo调用transactional时,它都应该使用类型为Consumer<PersonRepo>的参数。但是,从上面的代码中可以看出,客户端需要添加generic来执行personRepo的操作

另一个解决方法是在类级别而不是方法级别添加泛型

class AbstractRepo<T extends AbstractRepo> {
    void transactional(Consumer<T> consumer) {
        
    }
}

class PersonRepo extends AbstractRepo<PersonRepo> {
 
}

public class Application {
    public static void main(String[] args) {
        var personRepo = new PersonRepo();
        personRepo.transactional(it -> {
            it.addPerson();
            it.addAddress();
        });
    }
}

现在,客户端可以调用transactional(),而无需添加泛型。但是,这使得代码比现在更加奇怪。我想我是以完全错误的方式来处理这个问题的。有更好的办法吗我想在超类中实现一个方法,该方法将其实现(调用)子类的使用者作为其参数


共 (0) 个答案