Reflection: Call of methods and fields in Java
Forums:
public class Car {
public int speed;
public void IncreaseSpeed(int value) {
speed += value;
}
}
Class carType = Class.forName("Vehicle.Car");
Object car = carType.newInstance();
Class[] paramTypes = new Class[] { int.class };
Object[] args = new Object[] { new Integer(10) };
Method method = carType.getMethod("IncreaseSpeed", paramTypes);
method.invoke(car, args);
Field field = carType.getField("speed");
int speed = field.getInt(car);
//speed is 10
- Log in to post comments