Four reflection artifact (b)

To manipulate the array using Reflected

 

Import the java.lang.reflect.Array; 

/ ** 
 * 
 * using reflection to manipulate the array 
 * / 
public  class ArrayTester { 

    public  static  void main (String [] args) throws a ClassNotFoundException { 
        Class classType The = the Class.forName ( "the java.lang. String " ); 

        Object array = Array.newInstance (classType the, 10); // Create a new array of the specified type and size of the component. 

        Array.set (Array, . 5, "Hello" ); 

        String STR = (String) Array.get (Array,. 5 ); 

        System.out.println (STR); 

    } 
}

 

 

We can note can make changes to the array java.lang.reflect.array, create an array.

 

For two-dimensional and even three-dimensional array, we can still be changed.

 

public  class ArrayTester2 { 

    public  static  void main (String [] args) {
         int [] = DIMS new new  int [] {. 5, 10, 15 }; 

        Object Array = Array.newInstance ( int . class , DIMS); 

        Object arrayObj = the Array .get (array,. 3 );
         // this case is a two-dimensional array arrayObj 

        Class <?> = CLS arrayObj.getClass () the getComponentType ();. 

        arrayObj = Array.get (arrayObj,. 5 );
         // this case the arrayObj is a one-dimensional array 

        Array.set (arrayObj, 10, 37 [);

        int[][][] arrayCast = (int[][][]) array;

        System.out.println(arrayCast[3][5][10]);
    }
 

 

It may be noted, line 8 is already a two-dimensional array get value, line 13 is a one-dimensional array to the value.

 

This is to some code in the third 3-dimensional array value of the fifth and tenth 37.

 

There is a interview questions, how to change private property in one approach, a get method.

 

public class PrivateTest {

    private String name = "hello";

    public String getName(){
        return this.name;
    }

 

 

How to change the name of the property value from the above that class?

 

public class ReflectionTest {
    public static void main(String[] args) throws Exception {
        PrivateTest pt = new PrivateTest();

        Class<?> clazz = PrivateTest.class;

        Field field = clazz.getDeclaredField("name");

        field.setAccessible(true);
        //压制java的访问控制检查

        System.out.println(field.get(pt));

        field.set(pt,"world");

        System.out.println(pt.getName());
    }
}

 

 

上面代码中,关键的一点是需要压制java的访问控制检查,如果不去压制,那么将会访问不到那个属性值,也就无法

 

更改为world,这其中利用了Java的反射机制,非常方便的就可以改变私有的属性值。

 
 

Guess you like

Origin www.cnblogs.com/xiaobaoa/p/12178521.html