Search code examples
javagenericsgeneric-function

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?


Solution

  • 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