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.
I was suprised myself, that you can access the Vehicle's Field by just casting ist to a Vehicle.
Your Approch works, you just have to go the last step by using the Field from the Vehicle-Class:
Audi audi = new Audi();
Vehicle vehicle = audi;
String audiSeries = audi.series;
System.out.println("direct-audi: " + audiSeries);
String vehicleSeries = vehicle.series;
System.out.println("direct-vehicle: " + vehicleSeries);
Class audiClass = Class.forName(Audi.class.getName());
Class vehicleClass = Class.forName(Vehicle.class.getName());
Object audiObj = audiClass.newInstance();
Field audiSeriesField = audiClass.getField("series");
Field vehicleSeriesField = vehicleClass.getField("series");
System.out.println("reflection-audi: " + audiSeriesField.get(audiObj));
System.out.println("reflection-vehicle: " + vehicleSeriesField.get(audiObj));
Result:
direct-audi: A8
direct-vehicle: Sedan
reflection-audi: A8
reflection-vehicle: Sedan
If you dont Know the Superclass Name you can just use Class vehicleClass = audiClass.getSuperclass();