简体   繁体   中英

Get type of Object from constructor for generic parameters?

private LinkedList register;

public Register(Object obj){
    register = new LinkedList<obj>();
}

So basically, can I define the type of objects that the LinkedList should contain through this method? (For Java)

Perhaps obj.getClass?

Generics can be confusing. I think you want this:

public class Register<T> {
    private LinkedList<T> register = new LinkedList<T>();

    public static <T> Register<T> create(T object) {
        return new Register<T>();
    }
}

Essentially no, generics are compile time only and need to be declared somewhere.

class Register<T> {
    LinkedList<T> register;

    Register(T obj) {
        register = new LinkedList<T>();
    }

You could, for example, use a factory method.

    static <U> Register<U> of(U obj) {
        Register<U> result = new Register<U>(obj);
        return result;
    }
}
Register<String> a = new Register<String>("abc");
Register<Double> b = Register.of(1.0d);

See also Lesson: Generics .

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