当前位置:网站首页>Reflection operation exercise

Reflection operation exercise

2022-07-06 21:01:00 zhang__ one thousand two hundred and thirty-four

Create a new file through reflection

package com.zqf.fanshe.Class_;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class reflection08 {
    
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    
        Class<?> fileClass = Class.forName("java.io.File");

        Constructor<?> declaredConstructor1 = fileClass.getDeclaredConstructor(String.class);
        String filepath="C:\\idea\\xiangmu\\newnew.txt";
        Object file = declaredConstructor1.newInstance(filepath);// establish File object 
        // Get method object 
        Method createNewFile = fileClass.getMethod("createNewFile");
        createNewFile.invoke(file);
        System.out.println(filepath.getClass());
        System.out.println(" File created successfully "+filepath);
    }
}

Modify the value of private attribute through reflection And call public methods

package com.zqf.fanshe.Class_;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class reflection07 {
    
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException {
    
        // obtain Test Object's Class object 
        Class<?> testClass = Class.forName("com.zqf.fanshe.Class_.Test");
        // Create an object instance 
        Object o = testClass.newInstance();
        // Get the attribute value 
        Field field = testClass.getDeclaredField("name");
        field.setAccessible(true);
        field.set(o,"hello jack");
        // Get public method getname
        Method method = testClass.getMethod("getName");
        Object invoke = method.invoke(o);
        System.out.println("name The value of the property "+invoke);
    }
}
class Test{
    
    private String name="hellokitty";

    public String getName() {
    
        return name;
    }
}

原网站

版权声明
本文为[zhang__ one thousand two hundred and thirty-four]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131132548924.html