首页 > 解决方案 > 从动态类中获取静态变量

问题描述

我对 Java 还很陌生,有些概念仍然很模糊,所以如果我的问题有点令人困惑,我很抱歉。

我有一堂食物,像这样:

public Class Food {

   // some unrelated methods and constructor

然后我有一堆 Food 类的子类,都带有一个静态变量“calories”:

public Class Banana extends Food{

    public static int calories = 100;

    // more unrelated methods and the constructor

和:

public Class Chicken extends Food{

    public static int calories = 300;

    // more unrelated methods and the constructor

等等...

如您所见,Food 的每个子类都有自己的静态“卡路里”变量,具有一些独特的值。还应注意,有时需要更改此卡路里变量;这就是为什么它不是const.

我还有另一个类 Eater:

public Class Eater {

    // constructor:

    public int mealcalories;

    public Eater(Class c) {

        this.mealcalories = c.calories;

如您所知,我想将一些 Food 子类的名称(例如 Banana)传递给 Eater 类实例的构造函数,如下所示:

public Eater myEater = new Eater(Banana.class);

然后 myEater 的“mealcalories”变量的值应该是 100。

然而,这不是正在发生的事情。我收到一条错误消息:

java: cannot find symbol
symbol: variable calories
location: variable c of type java.lang.Class

谁能帮我解决这个问题以及如何从我传入calories的任何类中正确获取变量?c

注意:这实际上不是我正在编码的内容,我只是对其进行了简化以使其更易于理解。

标签: javaclassdynamicreflectionstatic

解决方案


推荐阅读