-2

A.java

public class A<E> {

   Class cClass;

   public A(Class rClass) {
        this.cClass = rClass;
   }

   public E get() throws IllegalAccessException, InstantiationException {
        return (E) this.cClass.newInstance();
   }
}

A1.java

public class A1 extends A {}

I am trying to design a class A as generic and class A1 is a sub class of class A. Object creation should look something like this.

A<A1> a1 = new A<>();

I want provide a way that no one will create an object like this

A<B1> a1 = new A<>();

where class B1 is not a subclass of A.

How can i resolve this? Error

 error: constructor Operation in class A<E> cannot be applied to given types
Raghu DV
  • 258
  • 5
  • 18
  • You defined a constructor that takes an argument and called it with zero arguments. Where do *you* think the error came from? – Silvio Mayolo Dec 09 '17 at 04:59
  • Possible duplicate of [Java generalization - constructor cannot be applied to given types](https://stackoverflow.com/questions/39240079/java-generalization-constructor-cannot-be-applied-to-given-types) – vinS Dec 09 '17 at 05:01
  • Hey i didn't understand could you explain? @SilvioMayolo – Raghu DV Dec 09 '17 at 05:08
  • I understand class A requires a constructor, but how would i go about creating a constructor, that could take itself as an argument? I dont know i am missing something here – Raghu DV Dec 09 '17 at 05:13

1 Answers1

0

I don't know why you need such construction, but to make your code work, you should add class A<E extends A>, if you want

provide a way that no one will create an object like this A<B1> a1 = new A<>(); where class B1 is not a subclass of A.

public class A<E extends A> {

    private Class<E> cClass;

    public A() {
    }

    public A(Class<E> rClass) {
        this.cClass = rClass;
    }

    public E get() throws IllegalAccessException, InstantiationException {
        return this.cClass.newInstance();
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        A<A1> a = new A<>(A1.class);

        A1 a1 = a.get();

        //error
        //A<B1> a = new A<>();
    }
}

You can remove default constructor public A() {}, but then in your A1 class you have to add

public A1() {
    super(A1.class);
}

UPDATE: According to your comment, you want to get a class of a generic type at runtime, and that is not possible. Take a looke at this question

Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42