尝试了Java反射的 “.getDeclaredField” 方法,但仍然遇到了 “NoSuchFieldException”。

huangapple go评论158阅读模式
英文:

Tried Java reflection's ".getDeclaredField" method but still meet "NoSuchFieldException"

问题

这是我翻译的部分:

我正在尝试通过Java反射修改实例的字段。

以下是我的原始代码。

        for(Field f: customerClass.getDeclaredFields()) {
            System.out.println(f);
        }
        System.out.println("\n");

        System.out.println(customerClass.getDeclaredField("firstName"));

        for(int i=0; i < columnNames.length; i++) {
            System.out.println(columnNames[i]);
            field = customerClass.getDeclaredField(columnNames[i]);
            field.setAccessible(true);

以及结果。

private java.lang.String Customer.firstName
private java.lang.String Customer.lastName

private java.lang.String Customer.firstName
"firstName"
java.lang.NoSuchFieldException: "firstName"
        at java.lang.Class.getDeclaredField(Class.java:2070)

我想知道为什么 "customerClass.getDeclaredField("firstName")" 起作用,但 "customerClass.getDeclaredField(columnNames[i])" 抛出异常,因为 columnNames[0] == "firstName"。

英文:

I'm trying modification of an instance's fields through Java reflection.

Here is my original code.

        for(Field f: customerClass.getDeclaredFields()) {
            System.out.println(f);
        }
        System.out.println(&quot;\n&quot;);

        System.out.println(customerClass.getDeclaredField(&quot;firstName&quot;));

        for(int i=0; i &lt; columnNames.length; i++) {
            System.out.println(columnNames[i]);
            field = customerClass.getDeclaredField(columnNames[i]);
            field.setAccessible(true);

And the results.

private java.lang.String Customer.firstName
private java.lang.String Customer.lastName

private java.lang.String Customer.firstName
&quot;firstName&quot;
java.lang.NoSuchFieldException: &quot;firstName&quot;
        at java.lang.Class.getDeclaredField(Class.java:2070)

I am wondering why "customerClass.getDeclaredField("firstName")" works, but "customerClass.getDeclaredField(columnNames[i])" throws an Exception, since columnNames[0] == "firstName".

答案1

得分: 2

如果您查看columnNames[0]的输出,您会发现它不是firstName,而是&quot;firstName&quot;。去掉引号,它应该可以工作。

英文:

If you'll look at your output for columnNames[0], you'll see that it's not firstName, it's &quot;firstName&quot;. Remove the quotes and it should work.

huangapple
  • 本文由 发表于 2020年10月23日 11:09:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64493322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定