I am new to Java and trying to use Java reflection to set value to static final field in MuApiService
using private int field modifiers from java.lang.reflect.Field
.
I found below example code and trying to compile in JAVA 11.
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
But below Exception is thrown in Java 11 . Field class has a field called "modifiers" Could not figure out what is the issue here . It works for ArrayList , Set etc .
Time elapsed: 2.383 s <<< FAILURE!
java.lang.NoSuchFieldException: modifiers
at java.base/java.lang.Class.getDeclaredField(Class.java:2412)
Adding Code MyApiService.java
public class MyApiService extends RestApiService {
private MyApiService(String baseURL, String user, String password) {
super(baseURL, user, password);
}
/**
* Singleton holder class for the MyApiService object
*/
private static class SingletonHolder {
private static final ACPConfig ACP_CONFIG = (ACPConfig)
private static final Config PLATFORM_AO_CONFIG = ACP_CONFIG.newConfig
.getConfig(“def”)
.getConfig("abc”);
private static final String BASE_URL = PLATFORM_AO_CONFIG.getString("url");
private static final String USER = PLATFORM_AO_CONFIG.getString("user");
private static final String PASSWORD = PLATFORM_AO_CONFIG.getString("password");
private static final MyApiService INSTANCE = new MyApiService(BASE_URL, USER, PASSWORD);
}
/**
* Creates a singleton object of this class
*
* @return <code>MyApiService</code> singleton object
*/
public static MyApiService getInstance() {
return SingletonHolder.INSTANCE;
}
Test.java
for (Class nclass : MyApiService.class.getDeclaredClasses()) {
System.out.println("SimpleName is "+nclass.getSimpleName());
if (nclass.getSimpleName().equals("SingletonHolder")) {
sclass = nclass;
System.out.println(" sclass is " + sclass.getSimpleName());
for (Field field : sclass.getDeclaredFields()) {
System.out.println("Field names are " + field.getName());
}
setFinalStatic(sclass.getDeclaredField("PLATFORM_AO_CONFIG"), null);
setFinalStatic(sclass.getDeclaredField("USER "), null);
setFinalStatic(sclass.getDeclaredField(" PASSWORD"), null);
break;
}
}