英文:
How to get static final property from ClassName.class?
问题
I have array of classes like this.
private static final Class<?>[] CLASSES = new Class[]{
First.class,
Second.class,
};
Each class have property
public static final String PROPERTY = "property_name";
Need to make loop to compare `PROPERTY` with specific string like this:
for (Class<?> item : CLASSES) {
string.equals(item.PROPERTY)
}
But I couldn't find a way to escape from ".class" to get `item.PROPERTY`.
How to get `PROPERTY` in a correct way in this case?
Thanks!
英文:
I have array of classes like this.
private static final Class<?>[] CLASSES = new Class[]{
First.class,
Second.class,
};
Each class have property
public static final String PROPERTY = "property_name";
Need to make loop to compare PROPERTY
with specific string like this:
for (Class<?> item : CLASSES) {
string.equals(item.PROPERTY)
}
But I could't find a way to escape from ".class" to get item.PROPERTY
.
How to get PEOPERY
in a correct way in this case?
Thanks!
答案1
得分: 1
你应该使用:
for (Class<?> item : CLASSES) {
Field f = item.getDeclaredField("PROPERTY");
string.equals(f.get(item));
}
英文:
You should use:
for (Class<?> item : CLASSES) {
Field f = item.getDeclaredField("PROPERTY");
string.equals(f.get(item));
}
答案2
得分: 1
Did you mean how to deal with the exception?
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Class<?>[] classes = new Class[] { ClassA.class, ClassB.class, };
for (Class<?> item : classes) {
Field f = item.getDeclaredField("PROPERTY");
System.out.println(f.get(item));
}
}
public static void main(String[] args) {
Class<?>[] classes = new Class[] { ClassA.class, ClassB.class, };
for (Class<?> item : classes) {
try {
Field f = item.getDeclaredField("PROPERTY");
System.out.println(f.get(item));
} catch (Exception e) {
e.printStackTrace();
}
}
}
英文:
Did you mean how to deal with the exception?
enter code here
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Class<?>[] classes = new Class[] { ClassA.class, ClassB.class, };
for (Class<?> item : classes) {
Field f = item.getDeclaredField("PROPERTY");
System.out.println(f.get(item));
}
}
enter code here
public static void main(String[] args) {
Class<?>[] classes = new Class[] { ClassA.class, ClassB.class, };
for (Class<?> item : classes) {
try {
Field f = item.getDeclaredField("PROPERTY");
System.out.println(f.get(item));
} catch (Exception e) {
e.printStackTrace();
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论