Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Class objects in java

Tags:

java

class

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?

like image 612
amith murakonda Avatar asked Jan 03 '23 10:01

amith murakonda


1 Answers

Class<ITemplate> will strictly accept the ITemplate.class

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

like image 63
Yassin Hajaj Avatar answered Jan 11 '23 13:01

Yassin Hajaj