I have recently run into the following error which really confuses me. I have imported reflect. I have a class (called worker) with a field which is a private int called numOfJobs. In the constructor of Worker, numOfJobs is set to 0. Then, in a tester class, I create an instance of type worker:
waterBenders[0] = new Worker();
Field []fields = waterBenders[0].getClass().getDeclaredFields();
Field privateFieldJobs = fields[0];
privateFieldJobs.setAccessible(true);
try{
System.out.println(privateFieldJobs.get(waterBenders[0]));
System.out.println(privateFieldJobs.get(waterBenders[0]).getClass());
System.out.println((int)privateFieldJobs.get(waterBenders[0]));
}
It is the third line in the try box which is contains the error. The first two lines print:
0
class java.lang.Integer
This makes sense to me. However, if the object privateFieldJobs.get(waterBenders[0]) is an object of type Integer with "value" 0, then why should (int)privateFieldJobs.get(waterBenders[0]) throw the error:
Cannot cast from java.lang.Object to int
If I was to create a normal object of type Integer, then this type of casting usually works. What is so special about this example? I imagine it has something to do with the fact that this Integer object is coming from the fields array.
My worker class is essentially:
public class Worker extends Unit{
private int numOfJobs;
public Worker(Tile position, double hp, String faction) {
super(position, hp, 2, faction);
this.numOfJobs = 0;
}
public int getNumOfJobs(){
return this.numOfJobs;
}
}
Any help would be appreciated.
Workerclass?