package com.java.random.practice;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class App
{
private static final String ENCODING = "\\UTF-8";
public static void main( String[] args ) throws UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
{
URLEncoder.encode("anyValue", ENCODING);
}
}
Above code throws exception UnsupportedEncodingException when use "\" with encoding but when we use Reflection to modify the value then it does not show any exception, please see the below code:
package com.java.random.practice;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
public class App
{
private static final String ENCODING = "UTF-8";
public static void main( String[] args ) throws UnsupportedEncodingException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
{
App app=new App();
Field field = app.getClass().getDeclaredField("ENCODING");
field.setAccessible(true);
Field modifiersField =
Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true); modifiersField.setInt(field,
field.getModifiers() & ~Modifier.FINAL); field.set(null, "\\UTF-8");
String s= URLEncoder.encode("anyValue", ENCODING);
System.out.println(s);
}
}
Why this kind of strange behavior?
Aucun commentaire:
Enregistrer un commentaire