All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.jboss.weld.util.bytecode.ClassFileUtils Maven / Gradle / Ivy

There is a newer version: 3.0.0.Alpha1
Show newest version
/*
 * JBoss, Home of Professional Open Source
 * Copyright 2008, Red Hat, Inc., and individual contributors
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jboss.weld.util.bytecode;

import javassist.CannotCompileException;
import javassist.bytecode.ClassFile;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;

/**
 * Utility class for loading a ClassFile into a classloader. This borrows
 * heavily from javassist
 *
 * @author Stuart Douglas
 */
public class ClassFileUtils {
    private static java.lang.reflect.Method defineClass1, defineClass2;

    static {
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction() {
                public Object run() throws Exception {
                    Class cl = Class.forName("java.lang.ClassLoader");
                    defineClass1 = cl.getDeclaredMethod("defineClass", new Class[]{String.class, byte[].class, int.class, int.class});

                    defineClass2 = cl.getDeclaredMethod("defineClass", new Class[]{String.class, byte[].class, int.class, int.class, ProtectionDomain.class});
                    return null;
                }
            });
        } catch (PrivilegedActionException pae) {
            throw new RuntimeException("cannot initialize ClassPool", pae.getException());
        }
    }

    /**
     * Converts the class to a java.lang.Class object. Once this
     * method is called, further modifications are not allowed any more.
     * 

*

* The class file represented by the given CtClass is loaded by * the given class loader to construct a java.lang.Class object. * Since a private method on the class loader is invoked through the * reflection API, the caller must have permissions to do that. *

*

* An easy way to obtain ProtectionDomain object is to call * getProtectionDomain() in java.lang.Class. It * returns the domain that the class belongs to. *

*

* This method is provided for convenience. If you need more complex * functionality, you should write your own class loader. * * @param loader the class loader used to load this class. For example, the * loader returned by getClassLoader() can be used for * this parameter. * @param domain the protection domain for the class. If it is null, the * default domain created by java.lang.ClassLoader is * used. */ public static Class toClass(ClassFile ct, ClassLoader loader, ProtectionDomain domain) throws CannotCompileException { try { byte[] b = toBytecode(ct); java.lang.reflect.Method method; Object[] args; if (domain == null) { method = defineClass1; args = new Object[]{ct.getName(), b, new Integer(0), new Integer(b.length)}; } else { method = defineClass2; args = new Object[]{ct.getName(), b, new Integer(0), new Integer(b.length), domain}; } return toClass2(method, loader, args); } catch (RuntimeException e) { throw e; } catch (java.lang.reflect.InvocationTargetException e) { throw new CannotCompileException(e.getTargetException()); } catch (Exception e) { throw new CannotCompileException(e); } } public static byte[] toBytecode(ClassFile file) { try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(bytes); file.write(out); return bytes.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } } private static synchronized Class toClass2(Method method, ClassLoader loader, Object[] args) throws Exception { method.setAccessible(true); Class clazz = Class.class.cast(method.invoke(loader, args)); method.setAccessible(false); return clazz; } }