Load a class using reflection then edit the variab

2019-03-04 14:22发布

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: I have a button which when pressed it sets a variable (This is the class file). I want the java file which is loading this class to be able to see the new value of the variable read it, set it and do whatever is needed. And I want the new value which is set to show up on the running java class.

This is what I have tried so far but when I try to edit the values like getting baseX it doesn't show up on the running class. Also, the baseX value should change when I do stuff on the running class but the stuff is not printed to the screen when I change them. It's as if reflection can't read stuff on runtime. So what does?

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(baseX.get(instance));
            } else {
                System.out.println(loggedin);
                loggedIn.setBoolean(instance, true);
            }
        }

Also yeah getter/setter methods would work if they worked on runtime and I could make it so that when button x is pressed variable y changes on screen. What is a java bean? Also what if I wanted to just invoke a method and not get a value? Or what if I wanted to add my own methods/code?

1条回答
smile是对你的礼貌
2楼-- · 2019-03-04 15:13

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

  }
}
查看更多
登录 后发表回答