Java:如何在抽象类中引用子类的静态变量? [英] Java: How to refer to subclass's static variable in abstract class?

查看:460
本文介绍了Java:如何在抽象类中引用子类的静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于这个问题,我理解a的值在抽象类中声明的静态字段在所有子类中都是相同的。

I understand, thanks to this question, that the value of a static field declared in an abstract class will be the same among all subclasses.

上述问题的解决方案是在每个子类中声明一个静态字段,并在抽象类中声明一个

The solution in the aforementioned question is to declare a static field in each subclass, and an abstract "getter" instance method in the abstract class that must be implemented by each subclass.

但是我的抽象类中有一个静态方法,我需要引用该静态方法。子类的字段。我不能这样做,因为吸气剂是实例方法。

But I have a static method in my abstract class, and I need to refer to the static field of the subclass. I can't do this because the getter is an instance method.

这里最好的解决方案是什么?我不想在每个子类中放置几乎相同的 getAll 实例。

What's the best solution here? I'd rather not put nearly identical instances of getAll in every subclass.

public abstract class AbstractModel {

  public abstract String getTableName();

  public static ResultSet getAll() {

    Statement stmt = Database.get().conn.createStatement();

    // Error below: Cannot use "this" in static context.
    String query = "SELECT * FROM `" + this.getTableName() + "`";

    return stmt.executeQuery(query);
  }

}

public class Api extends AbstractModel {

  protected static final String TABLE_NAME = "apis";

  @Override
  public String getTableName() {
    return TABLE_NAME;
  }

}


推荐答案

我能够以这种方式编写代码,以最大程度地减少重新填充。

I was able to write the code in this way, to minimize repitition. It also eliminates the need for a getter.

public abstract class AbstractModel {

  public static ResultSet getAllFromTable(String tableName) {

    Statement stmt = Database.get().conn.createStatement();

    String query = "SELECT * FROM `" + tableName + "`";

    return stmt.executeQuery(query);
  }

}

public class Api extends AbstractModel {

  protected static final String TABLE_NAME = "apis";

  public static ResultSet getAll() {
    return getAllFromTable(TABLE_NAME);
  }

}

这篇关于Java:如何在抽象类中引用子类的静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆