0

I have an abstract Class:

 public abstract class BaseBean {

     public static String getTableName(){
        return "base";
     }
 }

And I have several Classes extending BaseBean, for Example:

public class User extends BaseBean {

    public static String getTableName(){
        return "user";
    }
}

(I think you already smell the Problem here)

Furthermore I have a generic Class:

public class GenericClass<T extends BaseBean> {

    public String getName(){
        return T.getTableName();
    }

}

What I want to do:

public class Main {

    public static void main(String [] args) {
        GenericClass<User> userClass = new GenericClass<>();
        String name = userClass.getName();
    }
}

Obvilously I want the String name to be "user" but it is "base". I searched a lot, and I know that I cannot overwrite static methods, but I don't know how to achieve it otherwise.

Any ideas?

trapzerapzerix
  • 135
  • 2
  • 10
  • 1
    You can not override static methods – Jens Mar 20 '17 at 15:09
  • Basically static methods can not be overridden. That is `GenericClass` will always use the `getTableName` method from `BaseBean` – dpr Mar 20 '17 at 15:10
  • I know, but this was not the question. Question is: How can I achieve what I want? – trapzerapzerix Mar 20 '17 at 15:17
  • Does it really have to be a static method? You could do it with reflection, but that would be extremely ugly. – Justas Mar 20 '17 at 15:20
  • I want to get the name from T, so I thought it needs to be static. As you see, a don't have an instance of T (User in this case) – trapzerapzerix Mar 20 '17 at 15:22
  • It looks like [X/Y problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Could you explain why you need such method? – Pshemo Mar 20 '17 at 15:31
  • You could try to use annotations and get the annotated value from your class object using reflection for example. However the snippets you posted very much look like you're trying to reinvent the wheel and should have a look at JPA. – dpr Mar 20 '17 at 19:59

0 Answers0