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()
接受供应商
),而
不要工作,因为作业有兼容性问题。ClassClassoh,嗯,好了:)哦,嗯,好了:)
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