Java Code Examples for org.apache.bcel.generic.ClassGen

The following examples show how to use org.apache.bcel.generic.ClassGen. These examples are extracted from open source projects. 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 Project: commons-bcel   Source File: id.java    License: 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 2
Source Project: commons-bcel   Source File: ElementValueGenTestCase.java    License: 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 3
Source Project: commons-bcel   Source File: PLSETestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * BCEL-262:
 */
public void testB262() throws ClassNotFoundException
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestEnum");
    final ClassGen gen = new ClassGen(clazz);
    final ConstantPoolGen pool = gen.getConstantPool();
    // get the values() method
    final Method m = gen.getMethodAt(0);
    final MethodGen mg = new MethodGen(m, gen.getClassName(), pool);
    final InstructionList il = mg.getInstructionList();
    // get the invokevirtual instruction
    final InstructionHandle ih = il.findHandle(3);
    final InvokeInstruction ii = (InvokeInstruction)(ih.getInstruction());
    // without fix, the getClassName() will throw:
    //   java.lang.IllegalArgumentException: Cannot be used on an array type
    final String cn = ii.getClassName(pool);
    assertEquals("[Lorg.apache.bcel.data.PLSETestEnum;", cn);
}
 
Example 4
Source Project: commons-bcel   Source File: PLSETestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * BCEL-295:
 */
public void testB295() throws Exception
{
    final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestClass2");
    final ClassGen cg = new ClassGen(clazz);
    final ConstantPoolGen pool = cg.getConstantPool();
    final Method m = cg.getMethodAt(1);  // 'main'
    final LocalVariableTable lvt = m.getLocalVariableTable();
    final LocalVariable lv = lvt.getLocalVariable(2, 4);  // 'i'
    //System.out.println(lv);
    final MethodGen mg = new MethodGen(m, cg.getClassName(), pool);
    final LocalVariableTable new_lvt = mg.getLocalVariableTable(mg.getConstantPool());
    final LocalVariable new_lv = new_lvt.getLocalVariable(2, 4);  // 'i'
    //System.out.println(new_lv);
    assertEquals("live range length", lv.getLength(), new_lv.getLength());
}
 
Example 5
/**
 * 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 6
/**
 * Creates a static field _sslContext of type {@link SSLSocketFactory}.
 *
 * @param classGen
 * @param constantPoolGen
 */
private static void createSslContextStaticField(ClassGen classGen, ConstantPoolGen constantPoolGen)
{
    FieldGen fieldGen = new FieldGen(ACC_PRIVATE | ACC_STATIC,
                                     Type.getType(SSLSocketFactory.class),
                                     SSL_SOCKET_FACTORY_FIELD,
                                     constantPoolGen);
    classGen.addField(fieldGen.getField());
}
 
Example 7
/**
 * Create a static method 'getDefault' returning {@link SocketFactory}
 * that creates a new instance of the sub-class and calls its no-argument
 * constructor, the newly created is returned to the caller.
 *
 * @param classGen
 * @param constantPoolGen
 * @param instructionFactory
 */
private static void createGetDefaultStaticMethod(ClassGen classGen,
        ConstantPoolGen constantPoolGen, InstructionFactory instructionFactory)
{
    InstructionList il = new InstructionList();

    String methodName = "getDefault";
    MethodGen mg = new MethodGen(ACC_STATIC | ACC_PUBLIC, // access flags
                        Type.getType(SSLSocketFactory.class),  // return type
                        new Type[0],   // argument types - no args
                        new String[0], // arg names - no args
                        methodName,
                        classGen.getClassName(),    // method, class
                        il,
                        constantPoolGen);

    il.append(instructionFactory.createNew(classGen.getClassName()));
    il.append(InstructionConst.DUP);

    il.append(instructionFactory.createInvoke(classGen.getClassName(), "<init>", Type.VOID,
                                   new Type[] {},
                                   INVOKESPECIAL));

    il.append(InstructionConst.ARETURN);

    mg.setMaxStack();
    classGen.addMethod(mg.getMethod());
    il.dispose();
}
 
Example 8
Source Project: gemfirexd-oss   Source File: ClassPathLoaderJUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
  ClassGen cg = new ClassGen(name, "java.lang.Object", "<generated>", Constants.ACC_PUBLIC | Constants.ACC_SUPER, null);
  cg.addEmptyConstructor(Constants.ACC_PUBLIC);
  JavaClass jClazz = cg.getJavaClass();
  byte[] bytes = jClazz.getBytes();
  return defineClass(jClazz.getClassName(), bytes, 0, bytes.length);
}
 
Example 9
/**
 * Test driver.
 */
public static void main(String[] argv) throws Exception {
    if (argv.length != 1) {
        System.err.println("Usage: " + BetterCFGBuilder2.class.getName() + " <class file>");
        System.exit(1);
    }

    String methodName = SystemProperties.getProperty("cfgbuilder.method");

    JavaClass jclass = new ClassParser(argv[0]).parse();
    ClassGen classGen = new ClassGen(jclass);

    Method[] methodList = jclass.getMethods();
    for (Method method : methodList) {
        if (method.isAbstract() || method.isNative()) {
            continue;
        }

        if (methodName != null && !method.getName().equals(methodName)) {
            continue;
        }

        MethodDescriptor descriptor = DescriptorFactory.instance().getMethodDescriptor(jclass, method);
        MethodGen methodGen = new MethodGen(method, jclass.getClassName(), classGen.getConstantPool());

        CFGBuilder cfgBuilder = new BetterCFGBuilder2(descriptor, methodGen);
        cfgBuilder.build();

        CFG cfg = cfgBuilder.getCFG();

        CFGPrinter cfgPrinter = new CFGPrinter(cfg);
        System.out.println("---------------------------------------------------------------------");
        System.out.println("Method: " + SignatureConverter.convertMethodSignature(methodGen));
        System.out.println("---------------------------------------------------------------------");
        cfgPrinter.print(System.out);
    }
}
 
Example 10
Source Project: gemfirexd-oss   Source File: ClassPathLoaderJUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
  ClassGen cg = new ClassGen(name, "java.lang.Object", "<generated>", Constants.ACC_PUBLIC | Constants.ACC_SUPER, null);
  cg.addEmptyConstructor(Constants.ACC_PUBLIC);
  JavaClass jClazz = cg.getJavaClass();
  byte[] bytes = jClazz.getBytes();
  return defineClass(jClazz.getClassName(), bytes, 0, bytes.length);
}
 
Example 11
Source Project: annotation-tools   Source File: BCELPerfTest.java    License: 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 12
Source Project: annotation-tools   Source File: BCELPerfTest.java    License: 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 13
Source Project: cougar   Source File: ComplexObjectCreator.java    License: 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 14
Source Project: cougar   Source File: ComplexObjectCreator.java    License: 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 15
Source Project: cougar   Source File: ComplexObjectCreator.java    License: 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 16
Source Project: commons-bcel   Source File: BCELBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
@Benchmark
public void generator(Blackhole bh) throws IOException {
    JarFile jar = getJarFile();

    for (JarEntry entry : getClasses(jar)) {
        byte[] bytes = IOUtils.toByteArray(jar.getInputStream(entry));

        JavaClass clazz = new ClassParser(new ByteArrayInputStream(bytes), entry.getName()).parse();

        ClassGen cg = new ClassGen(clazz);

        for (Method m : cg.getMethods()) {
            MethodGen mg = new MethodGen(m, cg.getClassName(), cg.getConstantPool());
            InstructionList il = mg.getInstructionList();

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

        bh.consume(cg.getJavaClass().getBytes());
    }

    jar.close();
}
 
Example 17
Source Project: commons-bcel   Source File: ElementValueGenTestCase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create primitive element values
 */
public void testCreateIntegerElementValue() throws Exception
{
    final ClassGen cg = createClassGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(
            ElementValueGen.PRIMITIVE_INT, cp, 555);
    // 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.lookupInteger(555),
            evg.getIndex() == cp.lookupInteger(555));
    checkSerialize(evg, cp);
}
 
Example 18
Source Project: commons-bcel   Source File: ElementValueGenTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void testCreateFloatElementValue() throws Exception
{
    final ClassGen cg = createClassGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(
            ElementValueGen.PRIMITIVE_FLOAT, cp, 111.222f);
    // 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.lookupFloat(111.222f), evg
            .getIndex() == cp.lookupFloat(111.222f));
    checkSerialize(evg, cp);
}
 
Example 19
Source Project: commons-bcel   Source File: ElementValueGenTestCase.java    License: 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 20
Source Project: commons-bcel   Source File: ElementValueGenTestCase.java    License: 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 21
Source Project: commons-bcel   Source File: ElementValueGenTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void testCreateCharElementValue() throws Exception
{
    final ClassGen cg = createClassGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(
            ElementValueGen.PRIMITIVE_CHAR, cp, 't');
    // Creation of an element like that should leave a new entry in the
    // cpool
    final int idx = cp.lookupInteger('t');
    assertTrue("Should have the same index in the constantpool but "
            + evg.getIndex() + "!=" + idx, evg.getIndex() == idx);
    checkSerialize(evg, cp);
}
 
Example 22
Source Project: commons-bcel   Source File: ElementValueGenTestCase.java    License: 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 23
Source Project: commons-bcel   Source File: ElementValueGenTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void testCreateBooleanElementValue() throws Exception
{
    final ClassGen cg = createClassGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(
            ElementValueGen.PRIMITIVE_BOOLEAN, cp, true);
    // Creation of an element like that should leave a new entry in the
    // cpool
    final int idx = cp.lookupInteger(1); // 1 == true
    assertTrue("Should have the same index in the constantpool but "
            + evg.getIndex() + "!=" + idx, evg.getIndex() == idx);
    checkSerialize(evg, cp);
}
 
Example 24
Source Project: commons-bcel   Source File: ElementValueGenTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void testCreateShortElementValue() throws Exception
{
    final ClassGen cg = createClassGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final SimpleElementValueGen evg = new SimpleElementValueGen(
            ElementValueGen.PRIMITIVE_SHORT, cp, (short) 42);
    // Creation of an element like that should leave a new entry in the
    // cpool
    final int idx = cp.lookupInteger(42);
    assertTrue("Should have the same index in the constantpool but "
            + evg.getIndex() + "!=" + idx, evg.getIndex() == idx);
    checkSerialize(evg, cp);
}
 
Example 25
Source Project: commons-bcel   Source File: ElementValueGenTestCase.java    License: 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 26
Source Project: commons-bcel   Source File: ElementValueGenTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void testCreateClassElementValue() throws Exception
{
    final ClassGen cg = createClassGen("HelloWorld");
    final ConstantPoolGen cp = cg.getConstantPool();
    final ObjectType classType = new ObjectType("java.lang.Integer");
    final ClassElementValueGen evg = new ClassElementValueGen(classType, cp);
    assertTrue("Unexpected value for contained class: '"
            + evg.getClassString() + "'", evg.getClassString().contains("Integer"));
    checkSerialize(evg, cp);
}
 
Example 27
Source Project: commons-bcel   Source File: TestReturn01Creator.java    License: 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 28
Source Project: commons-bcel   Source File: TestArrayAccess04Creator.java    License: 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 29
Source Project: commons-bcel   Source File: TestReturn03Creator.java    License: 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 30
Source Project: commons-bcel   Source File: TestArrayAccess02Creator.java    License: Apache License 2.0 5 votes vote down vote up
public TestArrayAccess02Creator() {
  _cg = new ClassGen(TEST_PACKAGE+".TestArrayAccess02", "java.lang.Object", "TestArrayAccess02.java",
          Const.ACC_PUBLIC | Const.ACC_SUPER, new String[] {  });

  _cp = _cg.getConstantPool();
  _factory = new InstructionFactory(_cg, _cp);
}