1

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 ?

Prakash Raman
  • 13,319
  • 27
  • 82
  • 132
  • You'll have to use the Reflection API for that. – Dragondraikk Jun 05 '15 at 11:40
  • Reflection. I don't know off the top of my head, but a 5-minute googling will give you many useful answers. – gd1 Jun 05 '15 at 11:40
  • That is just perverse. Anyway, take a look at the Reflection APIs. – TEK Jun 05 '15 at 11:41
  • Thanks :) Shall look at the reflection API :) – Prakash Raman Jun 05 '15 at 11:41
  • What are you trying to achieve, at a much higher level? Because the answer is probably to do something other than what you're trying to do. public fields are a huge design smell. – JB Nizet Jun 05 '15 at 11:41
  • You say "access by a getter'. In java that means to call a getter method, such as Rene M. suggested you. What you wrote in your example code is to call by a method name / access by variable name. You should not do it, unless you are sure that you need it. – AdamSkywalker Jun 05 '15 at 11:52
  • 1
    If its going about R class in android. Better look here: http://stackoverflow.com/questions/3476430/how-to-get-a-resource-id-with-a-known-resource-name Specialy this part: "public int getIdentifier (String name, String defType, String defPackage) " – Rene M. Jun 05 '15 at 13:13

2 Answers2

3
Test t = new Test();
System.out.println(t.getClass().getField("marks").get(t));
2

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[] {});
Karthigeyan Vellasamy
  • 2,038
  • 6
  • 33
  • 50