Consider the following scenario:
package packA;
public class A
{
private static int i = 0;
}
package packB;
public class B
{
public static void main(String[] args)
{
int i = A.i + 1;
}
}
Because A.i
is private
, it is not possible to access it from class B
, and doing so would cause a compiler error.
However, if I instrument the B
class like this
public class B
{
public static void main(String[] args)
{
// getstatic packA/A.i : I
// iconst_1
// iadd
// istore_1
}
}
And call the main
method, would the JVM verifier check if accessing A.i
is valid? Similarly, would it pass the following bytecode as valid if A.i
was declared final
?
public class B
{
public static void main(String[] args)
{
// iconst_2
// putstatic packA/A.i : I
}
}
I am wondering about this because the verifier would need to load the class to check the access flags of the fields. Also, if it doesn't verify them it would be possible to instrument malicious bytecode to change the values of fields or provide 'hack methods' that would allow accessing a field without reflection.