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<? extends Emp> 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 反射器的登录功能
最新推荐文章于 2026-01-03 01:53:35 发布
本文展示了如何在Java中使用反射API创建Emp类的对象,设置属性值并调用其login方法。
1215

被折叠的 条评论
为什么被折叠?



