001/*
002 * Copyright 2002-2014 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.instrument.classloading;
018
019import java.lang.instrument.ClassFileTransformer;
020
021import org.springframework.core.OverridingClassLoader;
022import org.springframework.lang.UsesJava7;
023
024/**
025 * Simplistic implementation of an instrumentable {@code ClassLoader}.
026 *
027 * <p>Usable in tests and standalone environments.
028 *
029 * @author Rod Johnson
030 * @author Costin Leau
031 * @since 2.0
032 */
033@UsesJava7
034public class SimpleInstrumentableClassLoader extends OverridingClassLoader {
035
036        static {
037                if (parallelCapableClassLoaderAvailable) {
038                        ClassLoader.registerAsParallelCapable();
039                }
040        }
041
042
043        private final WeavingTransformer weavingTransformer;
044
045
046        /**
047         * Create a new SimpleInstrumentableClassLoader for the given ClassLoader.
048         * @param parent the ClassLoader to build an instrumentable ClassLoader for
049         */
050        public SimpleInstrumentableClassLoader(ClassLoader parent) {
051                super(parent);
052                this.weavingTransformer = new WeavingTransformer(parent);
053        }
054
055
056        /**
057         * Add a {@link ClassFileTransformer} to be applied by this ClassLoader.
058         * @param transformer the {@link ClassFileTransformer} to register
059         */
060        public void addTransformer(ClassFileTransformer transformer) {
061                this.weavingTransformer.addTransformer(transformer);
062        }
063
064
065        @Override
066        protected byte[] transformIfNecessary(String name, byte[] bytes) {
067                return this.weavingTransformer.transformIfNecessary(name, bytes);
068        }
069
070}