I will explain it through an example since I am not able to explain the problem.
Let's take 2 classes as below,
public class Vehicle {
public String series = "Sedan";
}
public class Audi extends Vehicle {
public String series = "A8";
}
Now, I want to get both the series of Vehicle and Audi. So I can use,
Audi audi = new Audi();
Vehicle vehicle = audi;
String audiSeries = audi.series; //This will give me "A8"
String vehicleSeries = vehicle.series; //This will give me "Sedan"
Here comes my problem: But If I don't have access to Vehicle
and Audi
classes during compilation and can only use reflection to get the object, how can I get the vehicle's series
.
Class audiClass = Class.forName("Audi");
Class vehicleClass = Class.forName("Vehicle");
Object audiObj = audiClass.newInstance();
Field audiSeries = audiClass.getField("series");
System.out.println(audiSeries.get(audiObj));
Output: A8
Is there anyway to get
Vehicle
class'series
field "Sedan" in the above method.
P.S: I cannot change the design to avoid this problem.
Aucun commentaire:
Enregistrer un commentaire