java 反射器的登录功能

package chapter03;

import java.lang.invoke.TypeDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test06 {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException, ClassNotFoundException {
       // Class  empClass = Emp.class;
        // Class empClass = new Emp().getClass();
        Class empClass = Class.forName("chapter03.Emp");
        Constructor declaredConstructor = empClass.getDeclaredConstructor();

        Object emp =declaredConstructor.newInstance();

        Field account = empClass.getField("account");
        Field password = empClass.getField("password");

        account.set(emp,"zhangsan");
        password.set(emp,"zhangsan");

        Method login = empClass.getMethod("login");
        Object result = login.invoke(emp);
        System.out.println(result);

    }
}
class Emp{
    public String account;
    public String password;

    public boolean login(){
        if("admin".equals(account) && "admin".equals(password))
        {
            return  true;
        }
        else {
            return  false;
        }
    }
}

你可能感兴趣的:(Java基础,java)