Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用'Class<;T>;`对于子类,其中T是父类_Java_Oop - Fatal编程技术网

Java 如何使用'Class<;T>;`对于子类,其中T是父类

Java 如何使用'Class<;T>;`对于子类,其中T是父类,java,oop,Java,Oop,假设我有以下设置 public class Parent{ } public class Child1 extends Parent{ } public class Child2 extends Parent{ } 我可以做到以下几点 Class<Parent> test = Parent.class Class test=Parent.Class 但是下面给了我一个错误 Class<Parent> test = Child1.class Class t

假设我有以下设置

public class Parent{

}

public class Child1 extends Parent{

}

public class Child2 extends Parent{

}
我可以做到以下几点

Class<Parent> test = Parent.class
Class test=Parent.Class
但是下面给了我一个错误

Class<Parent> test = Child1.class
Class test=Child1.Class
如何修复此问题?

试试这个

    Class<? extends Parent> test1 = Child1.class;
Class试试这个

    Class<? extends Parent> test1 = Child1.class;

Class其他人已经说过了

Class<? extends Parent> test1 = Child1.class;
现在我们使用它,并期望
Generic
在两个方向上都能正常工作:

Supplier<Integer> si = () -> 42;
Supplier<Number> sn = () -> 42;
Consumer<Integer> ci = n -> System.out.println(c);
Consumer<Number> cn = n -> System.out.println(c);

Generic<Integer> gi = new Generic<Integer>();
Generic<Number> gn = new Generic<Number>();

gi.accept(si); // works
gi.accept(sn); // won't work (1), that's ok
gi.put(ci); // works
gi.put(cn); // won't work (2), but should

gn.accept(si); // won't work (3), but should
gn.accept(sn); // works
gn.put(ci); // won't work (4), that's ok
gn.put(cn); // works
这两种方法都有效(
gi.put()
接受
消费者
gn.accept()
接受
供应商
),而


不要工作,因为作业存在兼容性问题。

其他人已经说过了

Class<? extends Parent> test1 = Child1.class;
现在我们使用它,并期望
Generic
在两个方向上都能正常工作:

Supplier<Integer> si = () -> 42;
Supplier<Number> sn = () -> 42;
Consumer<Integer> ci = n -> System.out.println(c);
Consumer<Number> cn = n -> System.out.println(c);

Generic<Integer> gi = new Generic<Integer>();
Generic<Number> gn = new Generic<Number>();

gi.accept(si); // works
gi.accept(sn); // won't work (1), that's ok
gi.put(ci); // works
gi.put(cn); // won't work (2), but should

gn.accept(si); // won't work (3), but should
gn.accept(sn); // works
gn.put(ci); // won't work (4), that's ok
gn.put(cn); // works
这两种方法都有效(
gi.put()
接受
消费者
gn.accept()
接受
供应商
),而


不要工作,因为作业有兼容性问题。

Class
Classoh,嗯,好了:)哦,嗯,好了:)
gi.put(cn); // (2)
gn.accept(si); // (3)
gi.accept(sn); // still won't work (1), that's ok
gn.put(ci); // still won't work (4), that's ok