Access objects variable & method by name

114 views Asked by At

Example class:

class Test {
  public int marks;
  public String location;

  public String show(){
      return "Good morning!";
  }
}

Is there a way I can access marks and locations by a getter? Maybe like so:

Test t = new Test();
System.out.println(t.get("marks"));

and maybe

System.out.println(t.call("show"));

The exact use case I have is to be able to access R.id.[fieldname] for accessing Android Resource ID

Can this work ?

R.id.getClass().getField("date").get(R.id) ?

How could I do this ?

2

There are 2 answers

4
AudioBubble On BEST ANSWER
Test t = new Test();
System.out.println(t.getClass().getField("marks").get(t));
0
Karthigeyan Vellasamy On

To invoke a method and get its value from some other class use this

Method method = obj.getClass().getMethod("Methodname", new Class[] {});
String output = (String) method.invoke(obj, new Object[] {});