我试图从将使用字符串设置的值(例如,来自application.properties文件中的值)填充一些application.properties,但在动态设置字段时无法让它传递值。
有什么简单的方法我可以做到这一点吗?我想我不是错过了一个Cast语句,就是不明白反射是如何工作的。谢谢。
import java.awt.RenderingHints;
import java.lang.reflect.Field;
...
// create the string we want to populate the hint from
String myHint = "VALUE_ANTIALIAS_ON";
// create the new hints that we want to populate
RenderingHints renderingHints = new RenderingHints(null);
// setting the value directly (like this) works:
renderingHints.put(RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
// but using reflection to retrieve the field:
Field hintField = RenderingHints.class.getField(myHint);
// doesn't work...
renderingHints.put(RenderingHints.KEY_ANTIALIASING, hintField);
// and gives the error:
// public static final java.lang.Object java.awt.RenderingHints.VALUE_ANTIALIAS_ON incompatible with Global antialiasing enable key发布于 2022-10-21 13:57:48
它不能工作,因为java.lang.reflect.Field的实例不是java.awt.RenderingHints的实例。您需要获得字段的值:
final Object hint = hintField.get(null);
renderingHints.put(RenderingHints.KEY_ANTIALIASING, hint);https://stackoverflow.com/questions/74154584
复制相似问题