Last active
December 7, 2015 02:24
-
-
Save JetXing/2aa575853eb94a15e1c4 to your computer and use it in GitHub Desktop.
Android 和 Java的java.lang.reflect.Field的API不一致,该方法适用于Java,通过反射方法更改final static 变量,http://stackoverflow.com/网站找到的,自己修改了一下,储存起来
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FinalVariateChangeByReflection { | |
public static final String HOST_NAME; | |
public static final String HOST_NAME_CHANGE = "http://www.apple.com"; | |
private static final String MODIFY_PERMISSION_FIELD = "modifiers"; | |
static { | |
HOST_NAME = "http://www.google.com"; | |
} | |
public static void main(String[] args) { | |
System.out.println(FinalVariateChangeByReflection.HOST_NAME); | |
changeFinalStatic(); | |
} | |
public static void changeFinalStatic() { | |
Field staticFinalField = null; | |
try { | |
staticFinalField = FinalVariateChangeByReflection.class.getDeclaredField("HOST_NAME"); | |
staticFinalField.setAccessible(true); | |
} catch (NoSuchFieldException e) { | |
e.printStackTrace(); | |
} | |
// Modify the final using reflection | |
Field modifiersField = null; | |
try { | |
modifiersField = Field.class.getDeclaredField(MODIFY_PERMISSION_FIELD); | |
modifiersField.setAccessible(true); | |
try { | |
modifiersField.setInt(staticFinalField, staticFinalField.getModifiers() & ~Modifier.FINAL); | |
} catch (IllegalAccessException e) { | |
e.printStackTrace(); | |
} | |
} catch (NoSuchFieldException e) { | |
e.printStackTrace(); | |
} | |
try { | |
staticFinalField.set(FinalVariateChangeByReflection.class, HOST_NAME_CHANGE); | |
} catch (IllegalAccessException e) { | |
e.printStackTrace(); | |
} | |
System.out.println(FinalVariateChangeByReflection.HOST_NAME); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment