001/* 002 * Copyright 2002-2017 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.Nullable; 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 */ 033public class SimpleInstrumentableClassLoader extends OverridingClassLoader { 034 035 static { 036 ClassLoader.registerAsParallelCapable(); 037 } 038 039 040 private final WeavingTransformer weavingTransformer; 041 042 043 /** 044 * Create a new SimpleInstrumentableClassLoader for the given ClassLoader. 045 * @param parent the ClassLoader to build an instrumentable ClassLoader for 046 */ 047 public SimpleInstrumentableClassLoader(@Nullable ClassLoader parent) { 048 super(parent); 049 this.weavingTransformer = new WeavingTransformer(parent); 050 } 051 052 053 /** 054 * Add a {@link ClassFileTransformer} to be applied by this ClassLoader. 055 * @param transformer the {@link ClassFileTransformer} to register 056 */ 057 public void addTransformer(ClassFileTransformer transformer) { 058 this.weavingTransformer.addTransformer(transformer); 059 } 060 061 062 @Override 063 protected byte[] transformIfNecessary(String name, byte[] bytes) { 064 return this.weavingTransformer.transformIfNecessary(name, bytes); 065 } 066 067}