001/*
002 * Copyright 2002-2013 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;
018
019import java.lang.instrument.Instrumentation;
020
021/**
022 * Java agent that saves the {@link Instrumentation} interface from the JVM
023 * for later use.
024 *
025 * @author Rod Johnson
026 * @author Juergen Hoeller
027 * @since 2.0
028 * @see org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver
029 */
030public class InstrumentationSavingAgent {
031
032        private static volatile Instrumentation instrumentation;
033
034
035        /**
036         * Save the {@link Instrumentation} interface exposed by the JVM.
037         */
038        public static void premain(String agentArgs, Instrumentation inst) {
039                instrumentation = inst;
040        }
041
042        /**
043         * Save the {@link Instrumentation} interface exposed by the JVM.
044         * This method is required to dynamically load this Agent with the Attach API.
045         */
046        public static void agentmain(String agentArgs, Instrumentation inst) {
047                instrumentation = inst;
048        }
049
050        /**
051         * Return the {@link Instrumentation} interface exposed by the JVM.
052         * <p>Note that this agent class will typically not be available in the classpath
053         * unless the agent is actually specified on JVM startup. If you intend to do
054         * conditional checking with respect to agent availability, consider using
055         * {@link org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver#getInstrumentation()}
056         * instead - which will work without the agent class in the classpath as well.
057         * @return the {@code Instrumentation} instance previously saved when
058         * the {@link #premain} or {@link #agentmain} methods was called by the JVM;
059         * will be {@code null} if this class was not used as Java agent when this
060         * JVM was started or it wasn't installed as agent using the Attach API.
061         * @see org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver#getInstrumentation()
062         */
063        public static Instrumentation getInstrumentation() {
064                return instrumentation;
065        }
066
067}