我可以使用它,还是会有更好的方法?:
public static <T> void setIfNull(T o, T value) {
if(o == null) {
o = value;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑!:我改变了我的代码(通过阅读我只会'设置'局部变量):
@SuppressWarnings("unchecked")
public static <T> T set(Class<T> clazz, String path, Object value) {
T result = null;
try {
Field field = clazz.getDeclaredField(path);
field.setAccessible(true);
field.set(null, value);
result = (T) field.get(null);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
最终编辑:我使用上面"编辑"中的代码解决了问题.