0

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?

nabster
  • 1,561
  • 2
  • 20
  • 32
Shahin Shemshian
  • 356
  • 1
  • 11
  • If you will always pass an instance of type `A` to `method_b` why does it have to be generic? It can just be `method_b(A m)` – Thiyagu Sep 28 '19 at 06:18
  • You are confused as to what a generic type is; also, your naming conventions of `class A` and `Class A` are quite confusing. Please expand on how you intend to use this. You want to call `B.calling_this()` and have it invoke `method_a()` on some non-existent instance of `A`? Why? – Elliott Frisch Sep 28 '19 at 06:19
  • 1
    @nabster Worst suggestion ever. Why even bother with generics, if you're just going to bypass type safety and cast everything? You might as well just define parameter as `Object`. – Andreas Sep 28 '19 at 06:35
  • Actually I made my code simple showing only the way I'm doing it. I'm using JPA repository to get data and do similar tasks so I just want to use one function but using different repository instance. @user7 – Shahin Shemshian Sep 28 '19 at 06:42
  • @ElliottFrisch I described in my last comment. – Shahin Shemshian Sep 28 '19 at 06:49

2 Answers2

3

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?

Martin'sRun
  • 522
  • 3
  • 11
2

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

josejuan
  • 9,338
  • 24
  • 31