简体   繁体   中英

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? 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. makePair2 does so directly but at the end, makePair3 uses getClass which isolates where the casting is required.

    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());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM