英文:
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("\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);
And the results.
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)
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
,而是"firstName"
。去掉引号,它应该可以工作。
英文:
If you'll look at your output for columnNames[0]
, you'll see that it's not firstName
, it's "firstName"
. Remove the quotes and it should work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论