Java 字段存在时的NoSuchFieldException

Java 字段存在时的NoSuchFieldException,java,reflection,Java,Reflection,尝试运行以下方法时,我得到一个java.lang.NoSuchFieldException: public void getTimes(String specialty, String day) { ArrayList<Tutor> withSpec = new ArrayList<Tutor>(); for (Tutor t : tutorList){ try { Time startTime = (Time)t

尝试运行以下方法时,我得到一个
java.lang.NoSuchFieldException

 public void getTimes(String specialty, String day) {
    ArrayList<Tutor> withSpec = new ArrayList<Tutor>();
    for (Tutor t : tutorList){
        try {
            Time startTime = (Time)t.getClass().getField(day + "Start").get(t);
        } catch (NoSuchFieldException | SecurityException | IllegalAccessException ex) Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex); }

我只是在学习使用反射,所以我确信这是某种语法错误…

该方法仅在字段是
公共的情况下才能找到该字段。您将需要改用该方法,该方法将查找直接在类上声明的任何字段,即使根据javadoc,
class.getField()
“返回反映此
对象所表示的类或接口的指定公共成员字段的
字段
对象。”。
如果要访问非公共字段,请使用
getDeclaredField()

解决
getClass().getField()问题的最佳方法是:

使用getDeclaredField()代替getField()

2) 将“HelloWorld”替换为您的类名

    String propertyName = "name";
    HelloWorld.class.getDeclaredField(propertyName)
如果要获取列的注释长度

HelloWorld.class.getDeclaredField(propertyName).getAnnotation(Column.class).length()

我是根据题目来回答这个问题的。我在Android项目中遇到了相同的错误(
NoSuchFieldException
),但原因不同

因此,对于其他来到这里的人来说,此错误也可能是由Android Studio中的缓存不同步引起的。请转到文件>使缓存无效/重新启动…


另请参见

对于任何看到这一问题仍然无法解决的Android开发人员,检查Proguard是否已启用。如果已启用,则有可能问题的类正在被模糊化,您需要添加规则来防止这种情况发生。

即使在使用getField上的getDeclaredField之后,我也会得到此消息错误:-无法访问带有修饰符“private”的类成员ohh获取它。我需要使用setAccessible(true)即使在使用
getDeclaredField()
时,我也会获得
NoSuchFieldException
,即使在使用
setAccessible(true)后,也会出现“has private access”错误
.Example 1:
Field fieldy=rootElement.getClass().getDeclaredField(“name”);
抛出
NoSuchFieldException
。但是执行
Field[]fields=rootElement.getClass().getDeclaredFields();
允许我遍历字段,当我调用
Field.getName()
时,它返回“name”“。那交易是什么呢?解决了:看起来我必须尝试一下/抓住它。它使你的应用程序崩溃了吗?”?
    String propertyName = "name";
    HelloWorld.class.getDeclaredField(propertyName)
HelloWorld.class.getDeclaredField(propertyName).getAnnotation(Column.class).length()