我正在尝试扩展“接口的交叉点”。所以:我所遵循的示例是尝试查找RandomAccessFile (Implemented Interfaces: Closeable, DataInput, DataOutput, AutoCloseable )
和DataInputStream(Implemented Interfaces: Closeable, DataInput, AutoCloseable )
的超接口,因此我们至少在Closeable
和DataInput
上有一个交集(当然我可以与AutoCloseable
建立交集:
所以代码就像这样:
private static <I extends DataInput & Closeable> Person read(I source) {
try (I input = source) {
return new Person(input.readLine(), Integer.valueOf(input.readLine()));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
当我这样做时,效果很好:
public static void main(String[] args) throws IOException {
RandomAccessFile input = new RandomAccessFile("src\\main\\resorces\\person.txt", "rw");
Person person2 = read(input);
System.out.println(person2.toString());
}
但是当我这样做时:
public static void main(String[] args) throws IOException {
DataInputStream stream = new DataInputStream(new
FileInputStream("src\\main\\resorces\\person.txt"));
Person person = read(stream);
System.out.println(person.toString());
}
它让我感到厌恶:
Exception in thread "main" java.lang.NoSuchMethodError: `java.io.DataInput.close()V
at com.test.java8.l03.generics.Person.read(Person.java:34)
at com.test.java8.l03.generics.Person.main(Person.java:20)
以下是所有代码:
public class Person {
public static void main(String[] args) throws IOException {
/*DataInputStream stream = new DataInputStream(new FileInputStream("src\\main\\resorces\\person.txt"));
Person person = read(stream);
System.out.println(person.toString());*/
RandomAccessFile input = new
RandomAccessFile("src\\main\\resorces\\person.txt", "rw");
Person person2 = read(input); System.out.println(person2.toString());
}
private static <I extends DataInput & Closeable> Person read(I source) {
try (I input = source) {
return new Person(input.readLine(), Integer.valueOf(input.readLine()));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private static Person read(RandomAccessFile source) {
try (RandomAccessFile input = source) {
return new Person(input.readLine(), Integer.valueOf(input.readLine()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
我不希望这个错误,因为交叉接口我扩展了Closeable。任何人都可以帮我这个吗?
但是不会抛出置换异常的接口:
private static <I extends Closeable & DataInput> Person read(I source) {
try (I input = source) {
return new Person(input.readLine(), Integer.valueOf(input.readLine()));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
接口的交集是否可能不是等价关系(更准确地说,此操作数上的交集不是自反的)并且编译器将左侧接口作为返回值?
与此相关:DataInputStream实现DataInput并扩展实现Closeable的抽象类InputStream。 RandomAccessFile直接实现DataInput和Closeable,因此RandomAccessFile必须实现close()方法而DataInputStream不实现(它可以使用实现Closeable接口的超类方法)?因此,使用动态方法调度时,编译器可能会混淆???