Simple use of reflection

Define a class to set parameter values ​​through reflection
public class Dept {

    private String deptCode;

    public String getDeptCode() {
        return deptCode;
    }

    public void setDeptCode(String deptCode) {
        this.deptCode = deptCode;
    }

   public static void main(String[] args) {
        Dept dept = new Dept();
        Class c = dept.getClass();
        try {
            Method setDepartmentCode = c.getMethod("setDeptCode",String.class); // Get the method object according to the method name and parameter type
            setDepartmentCode.invoke(dept,"2000"); // The first parameter is the class object, the following values ​​are parameter values, and no parameters are null
            System.out.println(dept.getDeptCode());
        } catch (NoSuchMethodException e) {
            e.printStackTrace ();
        } catch (IllegalAccessException e) {
            e.printStackTrace ();
        } catch (InvocationTargetException e) {
            e.printStackTrace ();
        }
    }
}

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325461313&siteId=291194637