我正在使用现有的旧spring引导代码,同时迁移/升级到spring引导2.7.16和jdk版本从8升级到21我得到这个错误
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.simple.AbstractJdbcCall;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
public class CustomJDBCCall extends SimpleJdbcCall {
private final CustomCallMetaDataContext callMetaDataContext;
private static final String CALL_META_DATA_CONTEXT = "callMetaDataContext";
private static final String MODIFIERS = "modifiers";
private static final Logger LOGGER =Logger.getLogger(CustomJDBCCall.class);
public CustomJDBCCall(JdbcTemplate jdbcTemplate) throws Exception {
super(jdbcTemplate);
try {
callMetaDataContext = new CustomCallMetaDataContext();
// Access private field
Field callMetaDataContextField =
AbstractJdbcCall.class.getDeclaredField(CALL_META_DATA_CONTEXT);
callMetaDataContextField.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField(MODIFIERS);
modifiersField.setAccessible(true);
modifiersField.setInt(callMetaDataContextField,
callMetaDataContextField.getModifiers() & ~Modifier.FINAL);
callMetaDataContextField.set(this, this.callMetaDataContext);
} catch (NoSuchFieldException | IllegalAccessException ex) {
LOGGER.error("Error while using custom JDBC", ex);
throw new RuntimeException("Exception thrown overriding
AbstractJdbcCall.callMetaDataContext field", ex);
} catch (Exception ex) {
LOGGER.error("Error while using custom JDBC", ex);
throw ex;
}
}
public List<SqlParameter> getParamerters() throws Exception {
return this.callMetaDataContext.getCallParameters();
}
}
字符串
在这段代码中,
Field modifiersField = Field.class.getDeclaredField(MODIFIERS);
型
原因:java.lang.NoSuchFieldException:modifiers at java.base/java.lang.Class.getDeclaredField(Class.java:2782)
之前它在jdk 8中工作正常。这是现有的代码不是我写的,我认为这里访问私有final字段并设置值。我对吗?我认为在Jdk版本12及以上修改final和私有变量是不可能的或禁用的,有没有任何工作?
1条答案
按热度按时间dxpyg8gm1#
在项目文件夹中添加了spring类AbstractJdbcCall.java,并使用确切的包名。然后添加以下方法以返回callMetaDataContext
字符串
现在CustomJDBCCall看起来像这样
型
这解决了我的问题。