Creating a Constructor in BCEL

O

oulan bator

hi,

I'm trying to write a class using BCEL from scratch and get error

Exception in thread "main" java.lang.InstantiationException:
org.apache.bcel.generic.ClassGen
at java.lang.Class.newInstance0(Unknown Source)

when I'm calling newInstance on this class. I guess that it's because I
did'nt write a default constructor.

How can I create a constructor in a class file using BCEL ?
Constructors are neither methods nor have a dedicated gen in BCEL api
like a constructor

thanks
 
O

oulan bator

I've got a partial answer to my question:

ClassGen has a method addEmptyConstructor(Constants.ACC_PUBLIC);

but it does not answer the whole one.
 
C

Chris Uppal

oulan said:
ClassGen has a method addEmptyConstructor(Constants.ACC_PUBLIC);

It's worth taking a look at the source for that method.

but it does not answer the whole one.

From the point of view of the JVM a constructor is just a method with a
specific name ("<init>") and a specific return type (void). It is also
required to call another constructor of the same class or its superclass before
it does anything much else. You'll see that the code for
ClassGen.addEmptyConstructor() generates a method which satisfies those
conditions.

-- chris
 
T

Thomas Hawtin

oulan said:
when I'm calling newInstance on this class. I guess that it's because I
did'nt write a default constructor.

If you save it to a file and use javap -c, you can see whether a
constructor has been included or not.
How can I create a constructor in a class file using BCEL ?
Constructors are neither methods nor have a dedicated gen in BCEL api
like a constructor

Constructors in the class file format are instance methods named
"<init>". The method body (except for java.lang.Object) must
invokespecial an "<init>" of the superclass, and all the usual restrictions.

Again, you can see constructors in real classes using javap -c. Also, I
believe BCEL contains a demo that takes a class file and produces (bad)
BCEL code to reconstruct it.

Tom Hawtin
 
O

oulan bator

all right, thanks for the answers.

If somebody is facing my problem, it does not come from any kind of
constructor problems, but is due to the used of ClassGen.getClass()
method instead of dump(File).
I didn't manage to load the created class without writing my own
classloader.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top