Shahin Shemshian
Shahin Shemshian

Reputation: 376

Use methods inside a generic type

Consider this class:

public class A {
   public void method_a(){
       System.out.println("THIS IS IT");
 }
}

I want to use 'method_a' in another function using generic type to get class A. for example:

public class B {
    public void calling_this(){
        A = new A();
        method_b(A);
    }
    public <T> void method_b(T m){
        m.method_a();
    }
}

I get error "cannot find symbol" on m.method_a(). Is this method possible or is there any thing like equivalent to it?

Upvotes: 0

Views: 64

Answers (2)

Martin&#39;sRun
Martin&#39;sRun

Reputation: 542

Define your method as

    public <T extends A> void method_b(T m){
        m.method_a();
    }

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

Upvotes: 3

josejuan
josejuan

Reputation: 9566

With generics you can set some restrictions

interface HasMethodA {
    void method_a();
}

...

class ... {

    <T extends HasMethodA> ... (..., T hasMethodA, ...) {
        ...
        hasMethodA.method_a();
        ...
    }

}

See Bounded Type Parameters

Upvotes: 2

Related Questions