I'm receiving this error:
java.lang.VerifyError: Bad <init> method call in method FooBar.<init>(I)V at offset 2
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2404)
at java.lang.Class.getConstructor0(Class.java:2714)
at java.lang.Class.getDeclaredConstructor(Class.java:2002)
when attempting to access the constructor of a class that I have modified with ASM 4.0 (using jdk7).
I have checked the bytecode for the initialization method of the class and it is as follows:
aload_0
iload_1
invokespecial com/foo/F/<init>(I)V
return
Decompiling the bytecode produces:
import com.foo.Foo;
public class FooBar extends Foo
{
public FooBar(int i)
{
super(i);
}
}
I'm completely stumped as to why I am receiving this error. I don't know if I've given enough information; please let me know if I can add any more information.
EDIT: Here is the code that is accessing the constructor:
Class fooBarClass = /* define class from class file bytes */;
Constructor fooBarConstructor = fooBarClass.getDeclaredConstructor(int.class);
EDIT2: Here is the code for the class Foo:
public class Foo extends F {
public Foo(int i) {
super(i);
}
}
Try to decompile class Foo and watch for the proper constructor. My bet is constructor Foo(int) does not exist.
The VerifyError is being thrown because the method that is being invoked in the constructor of class FooBar is actually the method of class F and not class Foo.
The constant pool reference to the super method in class FooBar was to the wrong class (i.e. F instead of Foo). Because of this, a VerifyError is thrown with the corresponding message "Bad method call".
Related
Given the following block of code i would like to understand why and how, emphasis on how, the method print in Subclass is invoked:
class Super {
Super() {
// what happens so that Sub's method print() is invoked
print();
}
public void print() {
System.out.println("in super");
}
}
class Sub extends Super {
Sub() {
super();
}
public void print() {
System.out.println("in sub");
}
}
public class TestClass {
public static void main(String[] args) {
Super s = new Sub(); // "in sub".. not so much expected
s.print(); // "in sub".. as expected
}
}
My understanding is that during compile time, classes will get V-table pointervtblPtrassociated with methods 'belonging' to a class.
Class Super should therefore have reference to it's own implementation of method print().
How come the method print() in Sub is invoked in constructor of Super? What really happens here ?
Here is what Super class looks like for the JVM (actually, that is the human-readable version obtained by javap -c Super)
class Super {
Super();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: invokevirtual #2 // Method print:()V
8: return
public void print();
Code:
0: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #4 // String in super
5: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return
}
as you can see, the print inside Super contructor was not resolved at compile time to Super::print. A virtual call means that it is resolved at runtime, with respect to class of this.
My understanding is that during compile time, classes will get V-table pointervtblPtrassociated with methods 'belonging' to a class. Class Super should therefore have reference to it's own implementation of method print().
You have a fundamental misunderstanding about virtual methods and overriding. In Java, every non-static, non-private method is virtual. Every virtual (normal) invocation of a virtual method, from anywhere, will invoke the version associated with the class of the object on which the method is invoked. That version might or might not be inherited, and might or might not override a superclass's method.
That a virtual method invocation is performed implicitly or explicitly on this in no way changes any of that. In particular, the actual class of the object being initialized is visible to every constructor, and provides the context for all their method invocations. In fact, this is why it's rarely a good idea for a constructor to invoke a virtual method provided by its own class. Superclass constructors run before subclass constructors, so if a superclass constructor invokes a method that happens to be overridden by a subclass, then that method will run before the object is fully initialized in the way that method may assume.
public class PrivateOverride {
private void f() {
System.out.println("private f()");
}
}
public class Derived extends PrivateOverride {
public void f() { //this method is never run.
System.out.println("public f()");
}
}
public static void main(String[] args) {
// instantiate Derived and assign it to
// object po of type PrivateOverride.
PrivateOverride po = new Derived();
// invoke method f of object po. It
// chooses to run the private method of PrivateOveride
// instead of Derived
po.f();
}
}
So, the output of this code is private f(). Now, the question arises to my mind: how can po which is an object of Derived Class call a private method of PrivateOverride which is its base class?
Because you defined the main method in PrivateOverride class. If you put the main method in Derived class, it would not compile, because .f() would not be visible there.
po.f() call in PrivateOverride class is not a polymorphism, because the f() in PrivateOverride class is private, so f() in Derived class is not overriden.
I do not really see the problem. That method is called ""within"" the class, this is pretty much expected.
This method is not overidden at all, instead it is shadowed by another one.
Methods in Java are dispatched depending on the static type of the receiver, which in this case is a PrivateOverride. Do not be confused by the fact that the po variable, by examining the code, can only hold a Derived instance at that line: only the declaration matters when available methods are searched.
And, by the way, the call to f() is not even translated into a virtual call in the final bytecode, because when the compiler looks for the potentially applicable methods in the class PrivateOverride, it only finds Object methods and the f() definition, which is only visible because the main() method is defined in PrivateOverride itself (see JLS 15.12)
I just went through the byte code of the compiled version of the above class and got the invokespecial Opcode. This Opcode was enough to tell the reason why the actual output is obvious. Invokespecial is used in three situations in which an instance method must be invoked based on the type of the reference, not on the class of the object. The three situations are:
1)invocation of instance initialization () methods
2)invocation of private methods
3)invocation of methods using the super keyword
Above example lies within the second scenario where we have invocation of private methods. So the method got invoked based on the the type of reference i.e PrivateOverride rather than type of class i.e Derived
So now the question arises why invokespecial? We have other Opcode like invokevirtual which gets invoked for method on the basis of classtype rather than reference type. So lets discuss why invokespecial Opcode is used for private methods. But we should know the difference between invokevirtual and invokespecial. Invokespecial differs from invokevirtual primarily in that invokespecial selects a method based on the type of the reference rather than the class of the object. In other words, it does static binding instead of dynamic binding. In each of the three situations where invokespecial is used, dynamic binding wouldn't yield the desired result.
When a method is invoked the JVM has to figure out what piece of code to execute: sometimes this is done at runtime (e.g. when overriding methods); sometimes this is done at compile time (e.g. when overloading methods). Once the JVM resolves what bit of code it is executing the actual instance that you are referring to isn't really any more significant than any other parameter.
The example code given sets up a scenario that may look like method overriding but isn't, so the method ends up getting bound at compile time. The private visibility modifier is not violated because the invocation doesn't touch any of Derived's code.
Looking at the bytecode (which the Java code is compiled to via javac) is instructive -
Say we slightly modify the original code to:
public class PrivateOverride {
private void f() {
System.out.println("private f()");
}
public static void main(String[] args) {
PrivateOverride po = new Derived();
po.f();
Derived d = new Derived();
d.f();
}
}
class Derived extends PrivateOverride {
public void f() {
System.out.println("public f()");
}
}
The main method compiles to (edited for brevity):
public static main([Ljava/lang/String;)V
NEW Derived
DUP
INVOKESPECIAL Derived.<init>()V
ASTORE 1
ALOAD 1
INVOKESPECIAL PrivateOverride.f()V
NEW Derived
DUP
INVOKESPECIAL Derived.<init>()V
ASTORE 2
ALOAD 2
INVOKEVIRTUAL Derived.f()V
RETURN
Notice that in each case the method is invoked on the compile time type. Notice also that the second call of f() uses the INVOKEVIRTUAL instruction. This is what tells the JVM to check the runtime type and decide what to call based on that.
It behaves this way because that is how the JVM was defined to behave in those cases.
The hard part is understanding what is going on and why.
You invoked the private method from within the class in which it was private. So the trojan horse is inside the castle, he can fiddle with the private variables. Take the trojan horse out of the castle and the private method is no longer visible.
This example might clear things up, Consider this program:
public class Bicycle {
private void getCost() {
System.out.println("200");
}
public static void main(String[] args) {
Bicycle ACME_bike = new ACME_bike();
ACME_bike.getCost();
Bicycle mybike = new Bicycle();
mybike.getCost();
ACME_bike acme_bike = new ACME_bike();
acme_bike.getCost();
//ACME_bike foobar = new Bicycle(); //Syntax error: Type mismatch:
//cannot convert from
//Bicycle to ACME_bike
}
}
class ACME_bike extends Bicycle {
public void getCost(){
System.out.println("700");
}
}
This program prints:
200
200
700
If you change the access modifier of getCost within Bicycle to public, protected, or package private(no modifier), Then it prints this:
700
200
700
There are four visibility levels in Java, package-level (implied by not using any visibility), public (everyone can call this), private (only I, and internal classes that see my functions as global, can call this), and protected (I, and any subclass, can call this).
You can either make your second class an internal class and then you don't override but simply call the function as if it's global (as far as the internal class is concerned), but then you can't really create instances wherever you want because it's a class that can be used exclusively by the owner (so if you want to use it elsewhere, the owner would need to be a factory and return it as if it's the base class) or you can make the method protected, and then the extending class can call the method.
I've this code snippet:
class Base {
public Base() {
method();
}
void method() {
System.out.println("In Base");
}
}
class Derived extends Base {
private String bar;
public Derived() {
bar="bar";
}
public void method() {
System.out.println(bar.length());
}
public static void main(String[] args) {
Base base=new Derived();
base.method();
}
}
On executing the code I got an exception:
Exception in thread "main" java.lang.NullPointerException
at Derived.method(Main.java:22)
at Base.<init>(Main.java:5)
at Derived.<init>(Main.java:17)
at Derived.main(Main.java:27)
I'm unable to understand why there is NullPointerException and the stackTrace of the exception. Anyone could help me to understand?
You can check the code here.
new Derived() creates a Derived object, which implies calling its super class constructor first, which in turn calls method - but you have overriden method so it is the child version of that method which is called. In that method, you call bar.length which has not been initialised yet.
Conclusion: it is almost never a good idea to call an overridable method in a constructor.
The code you have given is an antipattern. We should never invoke a method handling fields from a constructor for a simple reason that it might create unexpected results.
From your code, your are trying to initialize a field called bar in the Derived constructor. Now when you say Base b = new Derived(), the call happens in following fashion
Base static initializer -- If you have
Derived Static Initializer -- If you have
Base block initializer -- If you have
Base Constructor --> this is
the place you are calling method()
Derived Block initializer -- If you have
Derived constructor -->
this is the place where you are initializing bar
Now due to run time polymorphism, in to No. 4, when the Derived's method() gets called, the bar is not yet initialized to the value "bar" (since initialization happens at No. 6) , the NPE occurs
This question already has answers here:
Can a class have no constructor?
(7 answers)
Closed 7 years ago.
So when a class has a private constructor you can't initialize it, but when it doesn't have a constructor you can. So what is called when you initialize a class without a constructor?
As example, what is called here (new b())??
public class a {
public static void main(String args[]) {
b classB = new b();
}
}
public class b {
public void aMethod() {
}
}
There's no such thing as a "class without a constructor" in Java - if there's no explicit constructor in the source code the compiler automatically adds a default one to the class file:
public ClassName() {
super();
}
This in turn can fail to compile if the superclass doesn't have a public or protected no-argument constructor itself.
It's called the default constructor. It's automatically added when a class doesn't explicitly define any constructors.
Formal specification:
If a class contains no constructor declarations, then a default
constructor that takes no parameters is automatically provided:
If the class being declared is the primordial class Object, then the default
constructor has an empty body.
Otherwise, the default constructor takes no parameters and simply invokes the
superclass constructor with no arguments.
the default no argument constructor is invoked - see here for more information
When in doubt, use javap.
Empty.java:
public class Empty {
public static void main(String[] args) {}
}
Then:
javac Empty.java
javap -v Empty.class
Output excerpt:
public Empty();
descriptor: ()V
flags: ACC_PUBLIC
Code:
stack=1, locals=1, args_size=1
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
Ha! A constructor got generated. If we try the same for:
public class Empty {
public Empty() {}
public static void main(String[] args) {}
}
we see exactly the same bytecode.
I have asked if this is a Java-only restriction or if it is also present on the bytecode-level at: Is it valid to have a JVM bytecode class without any constructor?
There is an invisible default constructor that looks something like this:
public B() {
super();
}
When you call new B(), this implicit constructor gets called.
One note, in Java we use the convention that class names begin with an uppercase alphabetic character. So I have changed that for you.
I was playing around with anonymous subclasses and I found a problem that I can't get around.
EDIT: problem is solved thanks to thomas, the complete working code is on pastebin (Foo.java; FooTest.java)
2 Classes; Foo and FooTest...
Code first:
class Foo {
public Foo () {}
public void whichClassAmI () {
System.out.println(this.getClass());
}
public void say () {
System.out.println("Foo says: nothing");
}
public <T extends Foo> T getAnotherFoo () {
try {
Class<? extends Foo> c = this.getClass();
T r = (T)(c.getConstructor().newInstance());
return r;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
_
class FooTest {
public static String stuff = "";
public static void main (String[] args) {
Foo f1 = new Foo();
// instance of anon subclass
Foo f2 = new Foo(){
public void say () {
System.out.println("Modded Foo says: " + stuff);
}
};
f1.whichClassAmI();
f2.whichClassAmI();
stuff = "stuff";
f1.say();
f2.say();
Foo f3 = f1.getAnotherFoo();
f3.say();
Foo f4 = f2.getAnotherFoo(); // <-- exception here
}
}
So this code compiles with an unsafe operation warning, runs and throws an exception; output is:
Note: Foo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
class Foo
class FooTest$1
Foo says: nothing
Modded Foo says: stuff
Foo says: nothing
Exception in thread "main" java.lang.RuntimeException: java.lang.NoSuchMethodException: FooTest$1.<init>()
at Foo.getAnotherFoo(Foo.java:20)
at FooTest.main(FooTest.java:23)
Caused by: java.lang.NoSuchMethodException: FooTest$1.<init>()
at java.lang.Class.getConstructor0(Class.java:2723)
at java.lang.Class.getConstructor(Class.java:1674)
at Foo.getAnotherFoo(Foo.java:17)
... 1 more
what I don't understand is:
f2 class is FooTest$1 and this class seems to be not extending Foo
if (1) is true why does " Class c = [...] " can be set with FooTest$1
if (1) is false and (2) works correct, why doesn't it find the method?
To 1): f2 is of type FooTest$1 which extends Foo but that isn't printed, you just get the current class and no superclasses or interfaces.
To 2): Since 1) is false, there's not question here :)
To 3): The problem is that the annonymous inner class FooTest$1 needs an external FooTest instance to be created. Calling the constructor via reflection would try to create a new instance without an enclosing instance of FooTest and such a method is not available (i.e. a method that creates an instance of an inner class without an instance of the enclosing class).
What you need to do is get the constructor that takes an instance of the enclosing class as its parameter. For more information have a look at this question: Is it possible to create an instance of nested class using Java Reflection?
Edit:
I read your code again and am ashamed I missed this: the FooTest$1 class is actually a static inner class since it is created in the static main method. Thus it doesn't have a constructor taking an enclosing class instance.
However, since you create the class and its constructor inline that constructor isn't publicly visible. Thus getClass().getConstructor() won't return it (this class will only return public constructors. In that case you have to use getClass().getDeclaredConstructor(). The same is true for fields and methods, just for the record.