IT ESP
IT ESP

Reputation: 1

Generic Class Parameter in function

i have made a class like this

public class Item<IdType> {
    public IdType id;
    public String name;
}

public class Dealer<IdType> {
    public IdType id;
    public String name;
}

and a function in other class like this :

  public <T> boolean deleteById(Class<Class<T>> modelClass, T id) {
           daooperation();
           return true;
    }

what i want to do is when i call the function deleteById with parameter 1 is Item<Long> then parameter 2(id) should use Long datatype too other example is deleteById with parameter 1 is Dealer<String> then parameter 2(id) should use String datatype too. how to parse parameter 1(modelClass) to function deleteById or shoud i change the parameter 1(modelClass) in deleteById? please someone help me, show me how can i do that.

Upvotes: 0

Views: 106

Answers (3)

ice-phoenix
ice-phoenix

Reputation: 361

Due to the way type erasure and Java generics work, the best you can do is:

public class Test {

    public static <T extends WithId<B>, B> boolean foo(T obj, B id) {
        obj.id = id;
        return true;
    }

    public static void main(String[] args) {
        Bla<String> bar = new Bla<String>();
        foo(bar, "123"); // Works
        foo(bar,  123 ); // Fails
    }

}

abstract class WithId<T> {
    T id;
}

class Bla<T> extends WithId<T> {
    // ...
}

Upvotes: 0

pscuderi
pscuderi

Reputation: 1554

I think your methods should look more like this.

public static <I extends Item<T>, T> boolean deleteById(I item, T id) {
    doSomething();
    return true;
}

public static <D extends Dealer<T>, T> boolean deleteById(D dealer, T id) {
    doSomething();
    return true;
}

Upvotes: 1

Sashi Kant
Sashi Kant

Reputation: 13465

Object.Class method is your solution I guess

Upvotes: 0

Related Questions