java - 从动态类中获取静态变量
问题描述
我对 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
注意:这实际上不是我正在编码的内容,我只是对其进行了简化以使其更易于理解。
解决方案
推荐阅读
- javascript - 访问从 Express 中的 get 请求返回的对象中的元素时遇到问题
- html - 使 div 内的 div 响应式
- datepicker - 我的日期选择器没有出现。想知道我错过了什么
- apache-nifi - nifi:如何合并csv文件中的多列?
- java - 如何将不包含在第二个列表中且具有重复值的第一个列表的元素保存在列表中?
- html - 上传新内容时网页不会自动更新
- stylus - 如何将手写笔哈希表转换为 mixin
- android - 如何从 Fire DB 读取和存储 ArrayList 中的完整对象
- rust - 编译错误:找不到 `core` 的 crate
- python - 我该如何改进这个猜测算法?