0

I am looking for a BCEL code example on how to create an array of size 1 containing instances of java.lang.Class and initialize its only element with a reference to java.lang.String.class

in other terms, I am looking for a BCEL code sample to put "new Class[]{String.class}" on the stack.

Thanks.

entzik
  • 654
  • 4
  • 8

1 Answers1

1

Assuming that you want to create a class file version 49 (Java 5) or higher, the required instruction sequence is:

iconst_1
anewarrayjava/lang/Class
dup
iconst_0
ldcjava.lang.String.class
aastore

Now the only question left is how to generate that in BCEL. According to what I saw from its website, the generator code may look like this:

il.append(InstructionConstants.ICONST_1);
il.append(factory.createNewArray(Type.getType(Class.class), 1));
il.append(InstructionConstants.DUP);
il.append(InstructionConstants.ICONST_0);
il.append(new LDC(constantPoolGen.addClass(Type.getType(String.class))));
il.append(InstructionConstants.AASTORE);

Though I haven’t tested it.

Holger
  • 285,553
  • 42
  • 434
  • 765
  • thanks, unfortunately this throws: ClassGenException: Illegal type: class org.apache.bcel.generic.ObjectType – entzik Oct 20 '14 at 09:34
  • It seems that `factory.createConstant` can’t create `Class` constants. But I made some other mistakes in haste as well; I have fixed them now. – Holger Oct 20 '14 at 10:27