4

I have an Interface and 2 concrete class that implement that interface,

public interface ITemplate{}

public Template implements ITemoplate {}
public Template2 implements ITemplate {}

I have a method that takes in the Class object and instantiates it.

public addTemplate(Class<ITemplate> template){
    pipe.add(template.newInstance())
}

The problem is that when I call that method, it throws a compile time error:

instance.addTemplate(Template.class)

Compile Time Error :

addTemplate(java.package.ITemplate.class) cannot be applied to addTemplate(java.package.Template.class)

Am I missing something, or is there a work around for this?

0

2 Answers 2

8

Class<ITemplate> will strictly accept the ITemplate.class

Class<? extends ITemplate> will accept any of the classes implementing ITemplate.class

Sign up to request clarification or add additional context in comments.

Comments

1

try this method:

// works for all classes that inherit from ITemplate.
public addTemplate(Class< ? extends ITemplate> template){ 
    pipe.add(template.newInstance())
}

instead of

// only accepts ITemplate Type Class (Strict Type).
public addTemplate(Class<ITemplate> template){ 
    pipe.add(template.newInstance())
}

Here is an explanation: when you use Class<ITemplate> it is a strict type of class Itemplate. It will never take any other type argument other than ITemplate, because it is resolved at compile time only. However Class <? extends ITemplate> can accept all objects that are either ITemplate or have ITemplate as a superclass.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.