![](/img/trans.png)
[英]How to estimate execution time of method when it is invoked using Java Reflection
[英]How to retrieve an object from a method that is invoked using Java Reflection API?
我有一堂课:
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;
}
}
此类具有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;
}
}
所以我想做的是使用Java Reflection API中的invoke方法从Car类中调用getMotor()方法,但是我想获取Motor对象,以便可以从Motor类中调用getName()对象。 。 能做到吗? 也许不是通过获取Motor对象,而是以某种方式访问getName()方法。 有人可以帮我弄这个吗? 提前致谢。 到目前为止,这是我所做的:
Car c = new Car();
Class cClass = c.getClass();
cClass.getDeclaredMethod("getMotor").invoke(c, null);
这只会返回带有有关该方法的元数据的Method对象。
您几乎回答了自己的问题。 要获得Moter类的名称,您需要做的是这样的事情:
Car c = new Car();
Class cClass = c.getClass();
Object uncastedMotor = cClass.getDeclaredMethod("getMotor").invoke(c, null);
String motorName = ((Motor)uncastedMotor).getName();
请记住,如果方法不是无效的,则invoke方法可以返回Object。
同样,如果您拥有Car和VehicleClass类,那么更好的方法是创建一个新接口,声明特定于Car或VehicleClass的所有函数,并将getMotor添加到该接口。 然后,您可以使用instanceof验证对象是否属于此接口,并将其强制转换。 这是更简洁的代码,并确保在修改类后代码可以继续工作。
一般来说,使用反射是最后的选择。
只是做:
Motor m = (Motor) cClass.getDeclaredMethod("getMotor").invoke(c);
应该给你运动对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.