开发者

Java: How to access members of an object in a class hierarchy where one member changes its data type

开发者 https://www.devze.com 2023-03-25 08:46 出处:网络
I have three classes: class A { public Object Person; } class B exten开发者_JS百科ds A { } class C { public String Name;

I have three classes:

class A
{
  public Object Person;
}

class B exten开发者_JS百科ds A
{
}

class C
{
  public String Name;
}

I want to access Name:

B b = new B();
C c = new C();
c.Name = "John";

b.Person = c;
String s = b.Person.Name; // This is not allowed. Name is not a property of Person.

How can I reference the Name property (for either writing to it or reading from it)?

In fact, I could have a class D, E, F that I need to assign b.Person where each class has completely different properties. So the solution needs to work with class D, E, F, etc.


You need to cast:

String s = ((C)b.Person).Name;

Note this is a dangerous method of coding, since now changes to the datatype of Person in A could cause this code to throw an exception at runtime. You'd be much better off strongly-typing (i.e. using specific classes rather than Object) for your model.


You need to design a better object model. Using type 'Object' is too abstract, as already pointed out. At some point your code has to deal with a 'concrete' type. Java is a strongly typed programming language. Some other languages are more fluid and allow this kind of dynamic runtime typing.


You could considering use some Generics:

class A<T>
{
  public T person;
}

class B extends A<Person>
{
}

Or/And use some interfaces.

Anyway its a weird construction, you better just use a Person class where you can set the name. And in a object oriented way use some polymorphism.

I saw that you started a variable name with a capital letter, so a small tip: Use camel-casing (I fixed it in my example)


You should cast person to C if you want to access C's members (since Person is of the type Object):

String s = ((C)b.Person).Name;

Two notes:

  1. It is not recommended to declare members as public, but as private and declare getter / setter methods to access them.
  2. Usually member names start with lower case, not upper.


You can cast b to access the Name property;

String s = ((C)b.Person).Name


If your classes are beans you can use Commons BeanUtils to read the nested property:

BeanUtils.getNestedProperty(b, "person.name");

PS: Please try to use Java coding conventions: member names start with lowercase, properties are usualy private and exposed by get/set methods and so on.

0

精彩评论

暂无评论...
验证码 换一张
取 消