Load a class using reflection then edit the variables during runtime

狂风中的少年 提交于 2019-12-02 12:24:07

Try this:

public class Client {
  public Object baseX = new Object();
  public boolean loggedIn;
}
-----
public class Main {
  public static void main(String[] args) throws Exception {
    Class c = Class.forName("Client");
    /*for (Method m : c.getMethods()) {
      if (m.getName().contentEquals("main")) {
        Object[] passedArgs = {args};
        m.invoke(null, passedArgs);
      }

    }*/
    Object instance = c.newInstance();

    Field baseX = c.getField("baseX");
    Field loggedIn = c.getField("loggedIn");

    boolean gotValues = false;
    //while (!gotValues) {
      boolean loggedin = loggedIn.getBoolean(instance);
      if (loggedin) {
        System.out.println("Logged in!");
        System.out.println(baseX.get(instance));
      }
      else {
        System.out.println("NOT Logged in!");
        System.out.println(loggedin);
        loggedIn.setBoolean(instance, true);
        System.out.println(loggedIn.getBoolean(instance));
      }
    //}

  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!