[英]Java Generic Type new instance
public class PairT <T>{
public T first;
public T second;
public T getFirst() {
return first;
}
public void setFirst(T first) {
this.first = first;
}
public T getSecond() {
return second;
}
public void setSecond(T second) {
this.second = second;
}
public PairT(T first, T second) {
this.first = first;
this.second = second;
}
public PairT() {
}
What is the diffirence between these two makePair
methods essentially?这两种makePair
方法本质上有什么区别? Why the second one is grammatically illegal?为什么第二个在语法上是非法的?
First one:第一:
public static <U> PairT<U> makePair(Class<U> cl) throws Exception {
return new PairT<U>(cl.getConstructor().newInstance(),
cl.getConstructor().newInstance());
}
Second:第二:
public static <U> PairT<U> makePair(U cl) throws Exception {
return new PairT<U(
cl.getClass().getConstructor().newInstance(),
cl.getClass().getConstructor().newInstance());
}
Object.getClass()
returns Class<?>
, so you need to cast. Object.getClass()
返回Class<?>
,因此您需要强制转换。 makePair2
does so directly but at the end, makePair3
uses getClass
which isolates where the casting is required. makePair2
直接这样做,但最后, makePair3
使用getClass
来隔离需要强制转换的位置。
public static <U> PairT<U> makePair1(Class<U> cl) throws Exception {
return new PairT<U>(cl.getConstructor().newInstance(),
cl.getConstructor().newInstance());
}
public static <U> PairT<U> makePair2(U cl) throws Exception {
return new PairT<U>(
(U) cl.getClass().getConstructor().newInstance(),
(U) cl.getClass().getConstructor().newInstance());
}
private static <U> Class<U> getClass(U u) {
return (Class<U>) u.getClass();
}
public static <U> PairT<U> makePair3(U cl) throws Exception {
return new PairT<U>(
getClass(cl).getConstructor().newInstance(),
getClass(cl).getConstructor().newInstance());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.