I have become interested in reflection and I wrote a class to wrap an Object so that I can access its private instance fields. The code works great. I do not need to wory about the exceptions in the get()
and set()
methods because I cast the values appropriately through my wrappers accessor/mutators, but I was wondering if there is a better way of dealing with different types?
Example
public class Driver {
public static void main(String... args) {
Point p = new Point();
System.out.printf("Point initialized: %s\n", p);
PointDecorator mp = new PointDecorator(p);
mp.setX(2);
mp.setY(4);
p = mp.getPoint();
System.out.printf("Point updated: %s\n", p);
}
}
Output
Point initialized: (0, 0)
Point updated: (2, 4)
As you can see, I have modified the Point Objects fields, although they are inaccessible through traditional method calls. I was able to bypass Java's typechecking which I find both neat and dangerous. Does this mean that anyone can just wrap another persons class, unless it is immutable, and inject data?
Point.java
public class Point {
private int x, y;
public Point() {
this(0, 0);
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return String.format("(%d, %d)", x, y);
}
}
PointDecorator.java
import java.lang.reflect.Field;
public class PointDecorator extends Point {
protected Point point;
public PointDecorator(Point point) {
this.point = point;
}
public void setX(int x) {
set("x", x);
}
public int getX() {
return (Integer) get("x");
}
public void setY(int y) {
set("y", y);
}
public int getY() {
return (Integer) get("y");
}
public Point getPoint() {
return point;
}
protected Object get(String fieldName) {
try {
return field(fieldName).get(point);
} catch (Exception e) { }
return null;
}
protected void set(String fieldName, Object value) {
try {
field(fieldName).set(point, value);
} catch (Exception e) { }
}
private Field field(String fieldName) {
try {
Field f = point.getClass().getDeclaredField(fieldName);
f.setAccessible(true);
return f;
} catch (Exception e) { }
return null;
}
}