S
S
Sergey Tryapkin2020-01-22 10:52:53
Java
Sergey Tryapkin, 2020-01-22 10:52:53

Generic method that returns an instance of a new class?

Good afternoon.
Please help me understand generic methods.
There is such a design of classes.

class A {
    public A(String a) {
    }
}

class B extends A {
    public B(String b) {
        super(b);
    }
}

class C extends A {
    public C(String a) {
        super(a);
    }
}

The question is, how can you write a generic method so that you get a method of the form:
addRandomCart(B.class)
public <T extends A> T addRandomCart(Class<T> type) {
        String element = "element";
        A ps = new A(element);
        return (T) ps;
    }
}

Or maybe I'm thinking completely wrong? There can be many classes B, C.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmtm, 2020-01-22
@Dmtm

1) you can’t bring a parent to a child
2) if you really want a single method, then only through your ClassLoader

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question