Access a property of an object

-1

How to access the property of an object or a related object, using classmetadata or reflection?

Suppose we have these classes

class Person {    
    public String name;

    public void Person( name ) {
       this.name = name;
    }

}

class A {
    public String name;
    public void A(name) {
        this.name = name
    }
}

class B {
    public Person person;
    public void A(name) {
        this.person = new Person(name)
    }
}

As we can see, there are different ways to access the name property

For the first class:

A p = new A("Tom")
// Access to the name
p.name

For the second class

B p = new B("Tom")
// Access to the name
p.person.name

Now suppose that we need from a generic class to access the property name of the 2 classes, but the generic class does not know about this structure. This class would in some way need to access the information on how the structure is. Listen to something like metadata or reflection.

What would be the correct way to obtain and use this information?

    
asked by Matias 17.01.2017 в 05:24
source

2 answers

0

I recommend you use Reflection since it would also allow you to obtain values of private variables. I leave the link for you to take a look. Java Reflection Link

public class PrivateObject {

  private String privateString = null;

  public PrivateObject(String privateString) {
     this.privateString = privateString;
  }

}

And this is the part of Reflexion:

PrivateObject privateObject = new PrivateObject("The Private Value");
Field privateStringField = PrivateObject.class.getDeclaredField("privateString");

privateStringField.setAccessible(true); // Ponemos la variable publica

String fieldValue = (String) privateStringField.get(privateObject);
System.out.println("fieldValue = " + fieldValue);
    
answered by 18.01.2017 в 00:33
0

I recommend that you do not use the approximation that you indicate. The best thing is that you create an interface to obtain that data and implement it with the classes you want to respond to that generic class:

public interface Nombrable {
    public String getNombre();
}

And you implement it in your classes:

public class A implements Nombrable {
    String name;
    @Override
    public String getNombre() {
        return name;
    }
}

public class B implements Nombrable {
    @Override
    public String getNombre() {
        return person.name;
    }
}

This way you can access the name with the getNombre() method since you have defined that they implement that interface.

String nombreA = a.getNombre();
String nombreB = b.getNombre();

And you can also specify in your generic that they are of that type if you make the declaration as <T extends Nombrable>

    
answered by 20.01.2017 в 10:57