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?
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()returnsClass<?>, so you need to cast.makePair2does so directly but at the end,makePair3usesgetClasswhich isolates where the casting is required.