Java Code Examples for org.apache.bcel.generic.ClassGen#getConstantPool()

The following examples show how to use org.apache.bcel.generic.ClassGen#getConstantPool() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ElementValueGenTestCase.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public void testCreateEnumElementValue() throws Exception
{
    final ClassGen cg = createClassGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final ObjectType enumType = new ObjectType("SimpleEnum"); // Supports rainbow
                                                        // :)
    final EnumElementValueGen evg = new EnumElementValueGen(enumType, "Red", cp);
    // Creation of an element like that should leave a new entry in the
    // cpool
    assertTrue(
            "The new ElementValue value index should match the contents of the constantpool but "
                    + evg.getValueIndex() + "!=" + cp.lookupUtf8("Red"),
            evg.getValueIndex() == cp.lookupUtf8("Red"));
    // BCELBUG: Should the class signature or class name be in the constant
    // pool? (see note in ConstantPool)
    // assertTrue("The new ElementValue type index should match the contents
    // of the constantpool but "+
    // evg.getTypeIndex()+"!="+cp.lookupClass(enumType.getSignature()),
    // evg.getTypeIndex()==cp.lookupClass(enumType.getSignature()));
    checkSerialize(evg, cp);
}
 
Example 2
Source File: id.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    JavaClass clazz;

    if ((clazz = Repository.lookupClass(argv[0])) == null) {
        clazz = new ClassParser(argv[0]).parse(); // May throw IOException
    }

    final ClassGen cg = new ClassGen(clazz);

    for (final Method method : clazz.getMethods()) {
        final MethodGen mg = new MethodGen(method, cg.getClassName(), cg.getConstantPool());
        cg.replaceMethod(method, mg.getMethod());
    }

    for (final Field field : clazz.getFields()) {
        final FieldGen fg = new FieldGen(field, cg.getConstantPool());
        cg.replaceField(field, fg.getField());
    }

    cg.getJavaClass().dump(clazz.getClassName() + ".clazz");
}
 
Example 3
Source File: ComplexObjectCreator.java    From cougar with Apache License 2.0 5 votes vote down vote up
public ComplexObjectCreator(String objectType) {
  _cg = new ClassGen(objectType, "java.lang.Object", "ComplexObject.java", ACC_PUBLIC | ACC_SUPER, new String[] { "com.betfair.cougar.api.Result" });

  _cp = _cg.getConstantPool();
  _factory = new InstructionFactory(_cg, _cp);
  this.objectType = objectType;
}
 
Example 4
Source File: ElementValueGenTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public void testCreateByteElementValue() throws Exception
{
    final ClassGen cg = createClassGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(
            ElementValueGen.PRIMITIVE_CHAR, cp, (byte) 'z');
    // Creation of an element like that should leave a new entry in the
    // cpool
    final int idx = cp.lookupInteger((byte) 'z');
    assertTrue("Should have the same index in the constantpool but "
            + evg.getIndex() + "!=" + idx, evg.getIndex() == idx);
    checkSerialize(evg, cp);
}
 
Example 5
Source File: ElementValueGenTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public void testCreateLongElementValue() throws Exception
{
    final ClassGen cg = createClassGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(
            ElementValueGen.PRIMITIVE_LONG, cp, 3334455L);
    // Creation of an element like that should leave a new entry in the
    // cpool
    final int idx = cp.lookupLong(3334455L);
    assertTrue("Should have the same index in the constantpool but "
            + evg.getIndex() + "!=" + idx, evg.getIndex() == idx);
    checkSerialize(evg, cp);
}
 
Example 6
Source File: ElementValueGenTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public void testCreateDoubleElementValue() throws Exception
{
    final ClassGen cg = createClassGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(
            ElementValueGen.PRIMITIVE_DOUBLE, cp, 333.44);
    // Creation of an element like that should leave a new entry in the
    // cpool
    final int idx = cp.lookupDouble(333.44);
    assertTrue("Should have the same index in the constantpool but "
            + evg.getIndex() + "!=" + idx, evg.getIndex() == idx);
    checkSerialize(evg, cp);
}
 
Example 7
Source File: TestArrayAccess04Creator.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public TestArrayAccess04Creator() {
  _cg = new ClassGen(TEST_PACKAGE+".TestArrayAccess04", "java.lang.Object", "TestArrayAccess04.java",
          Const.ACC_PUBLIC | Const.ACC_SUPER, new String[] {  });

  _cp = _cg.getConstantPool();
  _factory = new InstructionFactory(_cg, _cp);
}
 
Example 8
Source File: TestArrayAccess03Creator.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public TestArrayAccess03Creator() {
  _cg = new ClassGen(TEST_PACKAGE+".TestArrayAccess03", "java.lang.Object", "TestArrayAccess03.java",
          Const.ACC_PUBLIC | Const.ACC_SUPER, new String[] {  });

  _cp = _cg.getConstantPool();
  _factory = new InstructionFactory(_cg, _cp);
}
 
Example 9
Source File: PLSETestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * BCEL-79:
 */
public void testB79() throws ClassNotFoundException
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestClass");
    final ClassGen gen = new ClassGen(clazz);
    final ConstantPoolGen pool = gen.getConstantPool();
    final Method m = gen.getMethodAt(2);
    final LocalVariableTable lvt = m.getLocalVariableTable();
    //System.out.println(lvt);
    //System.out.println(lvt.getTableLength());
    final MethodGen mg = new MethodGen(m, gen.getClassName(), pool);
    final LocalVariableTable new_lvt = mg.getLocalVariableTable(mg.getConstantPool());
    //System.out.println(new_lvt);
    assertEquals("number of locals", lvt.getTableLength(), new_lvt.getTableLength());
}
 
Example 10
Source File: LDAPSSLSocketFactoryGenerator.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the LDAPSocketFactoryImpl class (subclass of {@link AbstractLDAPSSLSocketFactory}.
 * A static method #getDefaulta, a static field _sslContent and no-arg constructor are added
 * to the class.
 *
 * @param className
 *
 * @return byte code
 */
private static byte[] createSubClassByteCode(final String className)
{
    ClassGen classGen = new ClassGen(className,
            AbstractLDAPSSLSocketFactory.class.getName(),
            "<generated>",
            ACC_PUBLIC | ACC_SUPER,
            null);
    ConstantPoolGen constantPoolGen = classGen.getConstantPool();
    InstructionFactory factory = new InstructionFactory(classGen);

    createSslContextStaticField(classGen, constantPoolGen);
    createGetDefaultStaticMethod(classGen, constantPoolGen, factory);

    classGen.addEmptyConstructor(ACC_PROTECTED);

    JavaClass javaClass = classGen.getJavaClass();
    ByteArrayOutputStream out = null;
    try
    {
        out = new ByteArrayOutputStream();
        javaClass.dump(out);
        return out.toByteArray();
    }
    catch (IOException ioex)
    {
        throw new IllegalStateException("Could not write to a ByteArrayOutputStream - should not happen", ioex);
    }
    finally
    {
        closeSafely(out);
    }
}
 
Example 11
Source File: ComplexObjectCreator.java    From cougar with Apache License 2.0 5 votes vote down vote up
public ComplexObjectCreator(String objectType) {
  _cg = new ClassGen(objectType, "java.lang.Object", "ComplexObject.java", ACC_PUBLIC | ACC_SUPER, new String[] { "com.betfair.cougar.api.Result" });

  _cp = _cg.getConstantPool();
  _factory = new InstructionFactory(_cg, _cp);
  this.objectType = objectType;
}
 
Example 12
Source File: PLSETestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * BCEL-208: A couple of methods in MethodGen.java need to test for
 * an empty instruction list.
 */
public void testB208() throws ClassNotFoundException
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestClass");
    final ClassGen gen = new ClassGen(clazz);
    final ConstantPoolGen pool = gen.getConstantPool();
    final Method m = gen.getMethodAt(1);
    final MethodGen mg = new MethodGen(m, gen.getClassName(), pool);
    mg.setInstructionList(null);
    mg.addLocalVariable("local2", Type.INT, null, null);
    // currently, this will cause null pointer exception
    mg.getLocalVariableTable(pool);
}
 
Example 13
Source File: BCELPerfTest.java    From annotation-tools with MIT License 5 votes vote down vote up
byte[] nullAdaptClass(final InputStream is, final String name)
        throws Exception
{
    JavaClass jc = new ClassParser(is, name + ".class").parse();
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
        boolean lv = ms[j].getLocalVariableTable() == null;
        boolean ln = ms[j].getLineNumberTable() == null;
        if (lv) {
            mg.removeLocalVariables();
        }
        if (ln) {
            mg.removeLineNumbers();
        }
        mg.stripAttributes(skipDebug);
        InstructionList il = mg.getInstructionList();
        if (il != null) {
            InstructionHandle ih = il.getStart();
            while (ih != null) {
                ih = ih.getNext();
            }
            if (compute) {
                mg.setMaxStack();
                mg.setMaxLocals();
            }
        }
        cg.replaceMethod(ms[j], mg.getMethod());
    }
    return cg.getJavaClass().getBytes();
}
 
Example 14
Source File: BCELPerfTest.java    From annotation-tools with MIT License 5 votes vote down vote up
byte[] nullAdaptClass(final InputStream is, final String name)
        throws Exception
{
    JavaClass jc = new ClassParser(is, name + ".class").parse();
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
        boolean lv = ms[j].getLocalVariableTable() == null;
        boolean ln = ms[j].getLineNumberTable() == null;
        if (lv) {
            mg.removeLocalVariables();
        }
        if (ln) {
            mg.removeLineNumbers();
        }
        mg.stripAttributes(skipDebug);
        InstructionList il = mg.getInstructionList();
        if (il != null) {
            InstructionHandle ih = il.getStart();
            while (ih != null) {
                ih = ih.getNext();
            }
            if (compute) {
                mg.setMaxStack();
                mg.setMaxLocals();
            }
        }
        cg.replaceMethod(ms[j], mg.getMethod());
    }
    return cg.getJavaClass().getBytes();
}
 
Example 15
Source File: ElementValueGenTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public void testCreateStringElementValue() throws Exception
{
    // Create HelloWorld
    final ClassGen cg = createClassGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(
            ElementValueGen.STRING, cp, "hello");
    // Creation of an element like that should leave a new entry in the
    // cpool
    assertTrue("Should have the same index in the constantpool but "
            + evg.getIndex() + "!=" + cp.lookupUtf8("hello"), evg
            .getIndex() == cp.lookupUtf8("hello"));
    checkSerialize(evg, cp);
}
 
Example 16
Source File: TestReturn01Creator.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public TestReturn01Creator() {
  _cg = new ClassGen(TEST_PACKAGE+".TestReturn01", "java.lang.Object", "TestReturn01.java",
          Const.ACC_PUBLIC | Const.ACC_SUPER, new String[] {  });

  _cp = _cg.getConstantPool();
  _factory = new InstructionFactory(_cg, _cp);
}
 
Example 17
Source File: TestReturn03Creator.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public TestReturn03Creator() {
  _cg = new ClassGen(TEST_PACKAGE+".TestReturn03", "java.lang.Object", "TestReturn03.java",
          Const.ACC_PUBLIC | Const.ACC_SUPER, new String[] {  });

  _cp = _cg.getConstantPool();
  _factory = new InstructionFactory(_cg, _cp);
}
 
Example 18
Source File: BCELPerfTest.java    From annotation-tools with MIT License 4 votes vote down vote up
byte[] counterAdaptClass(final InputStream is, final String name)
        throws Exception
{
    JavaClass jc = new ClassParser(is, name + ".class").parse();
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    if (!cg.isInterface()) {
        FieldGen fg = new FieldGen(ACC_PUBLIC,
                Type.getType("I"),
                "_counter",
                cp);
        cg.addField(fg.getField());
    }
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
        if (!mg.getName().equals("<init>") && !mg.isStatic()
                && !mg.isAbstract() && !mg.isNative())
        {
            if (mg.getInstructionList() != null) {
                InstructionList il = new InstructionList();
                il.append(new ALOAD(0));
                il.append(new ALOAD(0));
                il.append(new GETFIELD(cp.addFieldref(name, "_counter", "I")));
                il.append(new ICONST(1));
                il.append(new IADD());
                il.append(new PUTFIELD(cp.addFieldref(name, "_counter", "I")));
                mg.getInstructionList().insert(il);
                mg.setMaxStack(Math.max(mg.getMaxStack(), 2));
                boolean lv = ms[j].getLocalVariableTable() == null;
                boolean ln = ms[j].getLineNumberTable() == null;
                if (lv) {
                    mg.removeLocalVariables();
                }
                if (ln) {
                    mg.removeLineNumbers();
                }
                cg.replaceMethod(ms[j], mg.getMethod());
            }
        }
    }
    return cg.getJavaClass().getBytes();
}
 
Example 19
Source File: BCELPerfTest.java    From annotation-tools with MIT License 4 votes vote down vote up
byte[] counterAdaptClass(final InputStream is, final String name)
        throws Exception
{
    JavaClass jc = new ClassParser(is, name + ".class").parse();
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    if (!cg.isInterface()) {
        FieldGen fg = new FieldGen(ACC_PUBLIC,
                Type.getType("I"),
                "_counter",
                cp);
        cg.addField(fg.getField());
    }
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
        if (!mg.getName().equals("<init>") && !mg.isStatic()
                && !mg.isAbstract() && !mg.isNative())
        {
            if (mg.getInstructionList() != null) {
                InstructionList il = new InstructionList();
                il.append(new ALOAD(0));
                il.append(new ALOAD(0));
                il.append(new GETFIELD(cp.addFieldref(name, "_counter", "I")));
                il.append(new ICONST(1));
                il.append(new IADD());
                il.append(new PUTFIELD(cp.addFieldref(name, "_counter", "I")));
                mg.getInstructionList().insert(il);
                mg.setMaxStack(Math.max(mg.getMaxStack(), 2));
                boolean lv = ms[j].getLocalVariableTable() == null;
                boolean ln = ms[j].getLineNumberTable() == null;
                if (lv) {
                    mg.removeLocalVariables();
                }
                if (ln) {
                    mg.removeLineNumbers();
                }
                cg.replaceMethod(ms[j], mg.getMethod());
            }
        }
    }
    return cg.getJavaClass().getBytes();
}
 
Example 20
Source File: PerformanceTest.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
private static void test(final File lib) throws IOException {
    final NanoTimer total = new NanoTimer();
    final NanoTimer parseTime = new NanoTimer();
    final NanoTimer cgenTime = new NanoTimer();
    final NanoTimer mgenTime = new NanoTimer();
    final NanoTimer mserTime = new NanoTimer();
    final NanoTimer serTime = new NanoTimer();

    System.out.println("parsing " + lib);

    total.start();
    try (JarFile jar = new JarFile(lib)) {
        final Enumeration<?> en = jar.entries();

        while (en.hasMoreElements()) {
            final JarEntry e = (JarEntry) en.nextElement();
            if (e.getName().endsWith(".class")) {
                byte[] bytes;
                try (InputStream in = jar.getInputStream(e)) {
                    bytes = read(in);
                }

                parseTime.start();
                final JavaClass clazz = new ClassParser(new ByteArrayInputStream(bytes), e.getName()).parse();
                parseTime.stop();

                cgenTime.start();
                final ClassGen cg = new ClassGen(clazz);
                cgenTime.stop();

                final Method[] methods = cg.getMethods();
                for (final Method m : methods) {
                    mgenTime.start();
                    final MethodGen mg = new MethodGen(m, cg.getClassName(), cg.getConstantPool());
                    final InstructionList il = mg.getInstructionList();
                    mgenTime.stop();

                    mserTime.start();
                    if (il != null) {
                        mg.getInstructionList().setPositions();
                        mg.setMaxLocals();
                        mg.setMaxStack();
                    }
                    cg.replaceMethod(m, mg.getMethod());
                    mserTime.stop();
                }

                serTime.start();
                cg.getJavaClass().getBytes();
                serTime.stop();
            }
        }
    }
    total.stop();
    if (REPORT) {
        System.out.println("ClassParser.parse: " + parseTime);
        System.out.println("ClassGen.init: " + cgenTime);
        System.out.println("MethodGen.init: " + mgenTime);
        System.out.println("MethodGen.getMethod: " + mserTime);
        System.out.println("ClassGen.getJavaClass.getBytes: " + serTime);
        System.out.println("Total: " + total);
        System.out.println();
    }
}