简体   繁体   English

Java 与 generics 的接口是否可以强制执行通用类型?

[英]Is it possible for Java interface with generics to enforce the generic type?

Consider this example考虑这个例子

    public interface Equatable<T> {
        public boolean equal(T t1, T t2);
    }

    public class Square implements Equatable<Square> {
        public boolean equal(Square t1, Square t2) {
            return false;
        }
    }

Is it possible for the interface Equatable to enforce Square to implement an equal function that takes in two Squares, and not just two of any types (two Strings etc)?接口 Equatable 是否有可能强制 Square 实现一个相等的 function 接受两个 Square,而不仅仅是任何类型中的两个(两个 String 等)?

Yes, you didn't define what is "T" in your interface, you can limit it only to classes which implements Equatable, so String will not be allowed:是的,你没有在你的接口中定义什么是“T”,你可以将它限制在实现 Equatable 的类中,因此不允许使用String

public interface Equatable<T extends Equatable<T>>
{ 
     //...
}

Works Good:效果好:

public class Square implements Equatable<Square>
{
    public boolean equal(Square t1, Square t2)
    {
        return false;
    }
}

Compilation Error:编译错误:

public class Circle implements Equatable<String>
{
    public boolean equal(String t1, String t2)
    {
        return false;
    }
}

Note笔记
Pay attention, it's your responsibility to put in the brackets the same Type name, because below case will not be covered by compiler.请注意,您有责任将相同的类型名称放在括号中,因为编译器不会涵盖以下情况。
I guess you want to disallow to use equal method for different type.我猜你想禁止对不同类型使用相等的方法。

public class Square implements Equatable<Circle>
{
    public boolean equal(Circle t1, Circle t2)
    {
        return false;
    }
}

You can enforce this to an extent with a recursive generic type.您可以使用递归泛型类型在一定程度上强制执行此操作。

public interface Equatable<T extends Equatable<T>> {
    public boolean equal(T t1, T t2);
}

related:Java Enum definition相关:Java 枚举定义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM