Chen Kinnrot
Chen Kinnrot

Reputation: 21015

Java generics syntax issue

I want to write a method that gets 2 parameters:

  1. an interface.
  2. a class that implements that interface.

I want it to be generic (compile time type safe).

is there a way? if not, whats the alternative?

is there an option to get generic param that is an interface? ho do I declare it? ?

Upvotes: 0

Views: 88

Answers (2)

Jerome
Jerome

Reputation: 2184

public <T extends Interface> T myMethod(Interface I, Class<T> myClass) () {...}

if your method returns T

Upvotes: 2

PermGenError
PermGenError

Reputation: 46438

some thing like this ??

public <I, K extends I> void method(I i, K k){

    }

In the above method first parameter would be an interface, and second parameter would be any class that implements that interface.

    Interface1 i1;
    method(i1, class1); //class1 implements Interface1

In generics, interface implementation and class extending is represented using extends keyword. there is no implements keyword in the world of generics.

Upvotes: 5

Related Questions