I have a class:
package builderpattern;
import builderpattern.parts.Brakes;
import builderpattern.parts.Gearbox;
import builderpattern.parts.Motor;
import builderpattern.parts.Windshield;
public class Car extends VehicleClass implements IVehicle{
@Override
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
private Motor motor;
private Gearbox gearbox;
private Windshield windshield;
private Brakes brakes;
public Brakes getBrakes() {
return brakes;
}
public void setBrakes(Brakes brakes) {
this.brakes = brakes;
}
public Motor getMotor() {
return motor;
}
public void setMotor(Motor motor) {
this.motor = motor;
}
public Gearbox getGearbox() {
return gearbox;
}
public void setGearbox(Gearbox gearbox) {
this.gearbox = gearbox;
}
public Windshield getWindshield() {
return windshield;
}
public void setWindshield(Windshield windshield) {
this.windshield = windshield;
}
}
This class has a private field of the class Motor:
package builderpattern.parts;
public class Motor {
private double horsepower;
private String name;
private int numberOfCylinders;
public double getHorsepower() {
return horsepower;
}
public void setHorsepower(double horsepower) {
this.horsepower = horsepower;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumberOfCylinders() {
return numberOfCylinders;
}
public void setNumberOfCylinders(int numberOfCylinders) {
this.numberOfCylinders = numberOfCylinders;
}
public Motor(double horsepower, String name, int numberOfCylinders) {
super();
this.horsepower = horsepower;
this.name = name;
this.numberOfCylinders = numberOfCylinders;
}
}
So what I am trying to do is to invoke the getMotor() method from the class Car using the invoke method from the Java Reflection API, but I want to get the Motor object so I can invoke the getName() object from the Motor class. Can this be done? Maybe not by retrieving the Motor object, but somehow access the getName() method. Can someone help me with this? Thanks in advance. Here is what I have done so far:
Car c = new Car();
Class cClass = c.getClass();
cClass.getDeclaredMethod("getMotor").invoke(c, null);
This only returns a Method object with metadata about the method.
Aucun commentaire:
Enregistrer un commentaire