Load a class using reflection then edit the variables during runtime

后端 未结 1 456
刺人心
刺人心 2021-01-26 06:43

Okay, so I have a java file which is loading another class and I want the java file to be able to edit and read variables from the class which is running.

For example:

1条回答
  •  孤街浪徒
    2021-01-26 06:59

    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));
          }
        //}
    
      }
    }
    

    0 讨论(0)
提交回复
热议问题