Java 代理忽略应用程序类路径

Java Agent ignores application classpath

我正在编写我的第一个 java 代理,我遇到了一个问题,它没有加载我要附加代理的应用程序的 classes。

目前,代理很简单:

public class Main {

    public static void premain(String agentArgs, Instrumentation inst) {
        transformClass(inst);
    }

    public static void agentmain(String agentArgs, Instrumentation inst) {
        transformClass(inst);
    }

    private static void transformClass(Instrumentation instrumentation) {
        System.out.println("Hello from agent!");
        for (Class<?> clazz : instrumentation.getAllLoadedClasses()) {
            System.out.println(clazz.getName());
        }
    }

}

清单:

Manifest-Version: 1.0
Can-Set-Native-Method-Prefix: true
Premain-Class: com.dvelopp.agenttest.Main
Agent-Class: com.dvelopp.agenttest.Main
Can-Redefine-Classes: true
Can-Retransform-Classes: true

当我 运行 我的应用程序使用此代理时,它只打印它的 classes(不打印我的应用程序的主要 class)。

我的应用程序:

package com.dvelopp.agentconsumer;

public class Test {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

运行 结果:

java -javaagent:./agenttest/target/agent-test-1.0-SNAPSHOT-jar-with-dependencies.jar -cp ./agent-consumer/out/production/agent-consumer/ com.dvelopp.agentconsumer.Test
com.dvelopp.agenttest.Main
java.util.stream.FindOps$FindSink$OfRef$$Lambda/0x0000000800063440
java.util.stream.FindOps$FindSink$OfRef$$Lambda/0x0000000800063040
java.util.stream.FindOps$FindSink$OfRef$$Lambda/0x0000000800062c40
java.util.stream.FindOps$FindSink$OfRef$$Lambda/0x0000000800062840
jdk.internal.module.DefaultRoots$$Lambda/0x0000000800062440
java.util.stream.Collectors$$Lambda/0x0000000800062040
java.util.stream.Collectors$$Lambda/0x0000000800061c40
java.util.stream.Collectors$$Lambda/0x0000000800061840
java.util.stream.Collectors$$Lambda/0x0000000800061440
jdk.internal.module.DefaultRoots$$Lambda/0x0000000800061040
jdk.internal.module.DefaultRoots$$Lambda/0x0000000800060c40
jdk.internal.module.DefaultRoots$$Lambda/0x0000000800060840
java.lang.invoke.LambdaForm$MH/0x0000000800060440
jdk.internal.module.DefaultRoots$$Lambda/0x0000000800060040
sun.instrument.InstrumentationImpl
sun.security.util.Debug
java.security.SecureClassLoader$DebugHolder
java.security.BasicPermissionCollection
java.lang.RuntimePermission
java.security.UnresolvedPermission
java.security.AllPermission
java.io.FilePermissionCollection
java.io.FilePermissionCollection
java.security.Permissions
sun.security.util.FilePermCompat
java.io.FilePermission
jdk.internal.misc.JavaIOFilePermissionAccess
java.io.FilePermission
sun.net.www.MessageHeader
sun.net.www.protocol.file.FileURLConnection
sun.net.www.URLConnection
java.net.URLConnection
java.security.Permissions
java.security.PermissionCollection
java.security.SecureClassLoader
java.security.SecureClassLoader$CodeSourceKey
sun.nio.ByteBuffered
java.lang.Package$VersionInfo
java.lang.Package
java.lang.NamedPackage
java.util.jar.Attributes$Name
sun.nio.cs.StandardCharsets$Cache
sun.nio.cs.StandardCharsets$Aliases
sun.util.PreHashedMap
java.util.jar.Manifest$FastInputStream
java.util.jar.Attributes
java.lang.StringCoding$Result
jdk.internal.loader.URLClassPath$JarLoader
jdk.internal.loader.Resource
java.util.zip.ZipFile$InflaterCleanupAction
java.util.zip.Inflater$InflaterZStreamRef
java.util.zip.Inflater
java.util.zip.ZipFile$ZipFileInflaterInputStream
java.util.zip.InflaterInputStream
java.util.zip.ZipFile$ZipFileInputStream
java.util.jar.JarFile$JarFileEntry
java.util.jar.JarEntry
java.util.zip.ZipEntry
java.util.jar.JarFile
jdk.internal.util.jar.JarIndex
java.nio.DirectLongBufferU
java.nio.LongBuffer
java.nio.Bits
jdk.internal.misc.JavaNioAccess$BufferPool
java.util.concurrent.atomic.AtomicLong
java.nio.Bits
java.nio.DirectByteBuffer
java.nio.MappedByteBuffer
sun.nio.ch.DirectBuffer
jdk.internal.perf.PerfCounter$CoreCounters
jdk.internal.perf.Perf
jdk.internal.perf.Perf$GetPerfAction
jdk.internal.perf.PerfCounter
java.util.zip.ZipUtils
java.util.zip.ZipFile$Source$End
java.io.FileCleanable
[Ljava.lang.invoke.MemberName;
[Ljava.lang.invoke.VarHandle$AccessMode;
java.lang.invoke.VarHandle$AccessMode
[Ljava.lang.invoke.VarHandle$AccessType;
java.lang.invoke.VarHandle$AccessType
java.lang.invoke.VarForm
java.lang.invoke.VarHandleGuards
jdk.internal.util.Preconditions
java.lang.invoke.VarHandle
java.lang.invoke.VarHandleInts$FieldInstanceReadWrite
java.lang.invoke.VarHandleInts$FieldInstanceReadOnly
java.lang.invoke.VarHandles
java.util.concurrent.atomic.AtomicBoolean
java.io.RandomAccessFile
jdk.internal.misc.JavaIORandomAccessFileAccess
java.io.RandomAccessFile
java.io.DataInput
java.io.DataOutput
java.nio.file.attribute.FileTime
[Ljava.util.concurrent.TimeUnit;
java.util.concurrent.TimeUnit
sun.nio.fs.UnixFileAttributes$UnixAsBasicFileAttributes
[Lsun.nio.fs.NativeBuffer;
sun.nio.fs.NativeBuffer$Deallocator
sun.nio.fs.NativeBuffer
java.util.IdentityHashMap$KeySet
java.util.IdentityHashMap
jdk.internal.misc.TerminatingThreadLocal
sun.nio.fs.NativeBuffers
sun.nio.fs.NativeBuffers
sun.nio.fs.UnixFileAttributeViews$Basic
sun.nio.fs.AbstractBasicFileAttributeView
sun.nio.fs.DynamicFileAttributeView
sun.nio.fs.UnixFileAttributeViews
java.nio.file.attribute.BasicFileAttributeView
java.nio.file.attribute.FileAttributeView
java.nio.file.attribute.AttributeView
java.nio.file.Files
[Ljava.nio.file.LinkOption;
[Ljava.nio.file.CopyOption;
java.nio.file.LinkOption
java.nio.file.CopyOption
java.net.URI$Parser
java.nio.file.FileSystems$DefaultFileSystemHolder
java.nio.file.FileSystems$DefaultFileSystemHolder
[Ljava.nio.charset.CoderResult;
java.nio.charset.CoderResult
java.nio.HeapCharBuffer
java.nio.CharBuffer
java.lang.Readable
jdk.internal.misc.TerminatingThreadLocal
[Ljava.lang.ThreadLocal$ThreadLocalMap$Entry;
java.lang.ThreadLocal$ThreadLocalMap$Entry
java.lang.ThreadLocal$ThreadLocalMap
sun.nio.fs.UnixMountEntry 
jdk.internal.misc.JavaUtilZipFileAccess
java.util.zip.ZipFile
java.util.zip.ZipConstants
jdk.internal.loader.URLClassPath$JarLoader
jdk.internal.loader.URLClassPath$FileLoader
jdk.internal.loader.URLClassPath$Loader
java.util.concurrent.ConcurrentHashMap$ValueIterator
java.util.Enumeration
java.util.concurrent.ConcurrentHashMap$ValuesView
jdk.internal.loader.URLClassPath
java.security.PrivilegedExceptionAction
sun.util.locale.InternalLocaleBuilder$CaseInsensitiveChar
sun.util.locale.InternalLocaleBuilder
sun.util.locale.LocaleUtils
sun.util.locale.LocaleObjectCache$CacheEntry
sun.util.locale.BaseLocale$Key
sun.util.locale.BaseLocale$Cache
sun.util.locale.BaseLocale
java.util.Locale$Cache
sun.util.locale.LocaleObjectCache
java.util.Locale
sun.net.util.URLUtil
[Lsun.instrument.TransformerManager$TransformerInfo;
sun.instrument.TransformerManager$TransformerInfo
sun.instrument.TransformerManager
java.util.ArrayDeque$DeqIterator
java.lang.ClassLoader$NativeLibrary
java.lang.ClassLoader
sun.instrument.InstrumentationImpl
java.lang.instrument.Instrumentation
java.lang.InternalError
jdk.internal.module.ModuleBootstrap$SafeModuleFinder
jdk.internal.module.IllegalAccessLogger
jdk.internal.module.ModuleBootstrap
jdk.internal.module.IllegalAccessLogger$Builder
[Ljdk.internal.module.IllegalAccessLogger$Mode;
jdk.internal.module.IllegalAccessLogger$Mode
java.lang.ModuleLayer$Controller
jdk.internal.module.ServicesCatalog$ServiceProvider
java.util.concurrent.CopyOnWriteArrayList
java.util.concurrent.ConcurrentHashMap$ForwardingNode
jdk.internal.module.ModuleLoaderMap$Mapper
jdk.internal.module.ModuleLoaderMap
java.util.Collections$UnmodifiableRandomAccessList
java.util.Collections$UnmodifiableList
[Ljava.lang.module.ResolvedModule;
java.lang.module.ResolvedModule
java.util.Collections$UnmodifiableCollection
java.util.LinkedHashSet
java.util.HashMap$ValueIterator
java.util.HashMap$Values
java.lang.ModuleLayer
java.lang.module.ModuleFinder
[Ljava.nio.file.Path;
[Ljava.lang.Iterable;
[Ljava.nio.file.Watchable;
java.nio.file.Path
java.nio.file.Watchable
java.lang.module.Resolver
java.lang.module.Configuration
java.util.ImmutableCollections$Set12
java.util.stream.FindOps$FindOp
java.util.stream.FindOps$FindSink$OfRef
java.util.stream.FindOps$FindSink
java.util.stream.FindOps
java.util.stream.ReferencePipeline
java.util.stream.ReferencePipeline
java.util.stream.Sink$ChainedReference
java.util.stream.ReduceOpsReducingSink
java.util.stream.ReduceOps$Box
java.util.stream.ReduceOps$AccumulatingSink
java.util.stream.TerminalSink
java.util.stream.Sink
java.util.function.Consumer
java.util.stream.ReduceOps
java.util.stream.ReduceOps$ReduceOp
java.util.stream.TerminalOp
java.util.stream.ReduceOps
java.util.function.BinaryOperator
java.util.function.BiFunction
java.util.function.BiConsumer
java.lang.invoke.DirectMethodHandle$Interface
java.lang.invoke.DirectMethodHandle$Constructor
java.util.stream.Collectors$CollectorImpl
java.util.stream.Collector
java.util.Collections$UnmodifiableSet
java.util.Collections$UnmodifiableCollection
java.util.RegularEnumSet
java.util.EnumSet
[Ljava.util.stream.Collector$Characteristics;
java.util.stream.Collector$Characteristics
java.util.stream.Collectors
jdk.internal.org.objectweb.asm.FieldWriter
jdk.internal.org.objectweb.asm.FieldVisitor
java.util.stream.ReferencePipeline
[Ljava.util.stream.StreamShape;
java.util.stream.StreamShape
java.util.stream.ReferencePipeline
java.util.stream.ReferencePipeline$StatelessOp
jdk.internal.misc.InnocuousThread
jdk.internal.misc.InnocuousThread
[Ljava.security.ProtectionDomain;
jdk.internal.misc.InnocuousThread
jdk.internal.ref.CleanerFactory
jdk.internal.ref.CleanerImpl$CleanerCleanable
jdk.internal.ref.CleanerImpl$SoftCleanableRef
jdk.internal.ref.SoftCleanable
jdk.internal.ref.CleanerImpl$WeakCleanableRef
jdk.internal.ref.WeakCleanable
jdk.internal.ref.CleanerImpl$PhantomCleanableRef
jdk.internal.ref.PhantomCleanable
java.lang.ref.Cleaner$Cleanable
jdk.internal.ref.CleanerImpl
java.lang.ref.Cleaner
java.lang.ref.Cleaner
jdk.internal.ref.CleanerFactory
java.util.concurrent.ThreadFactory
jdk.internal.ref.CleanerFactory
java.util.ArrayList$Itr
java.lang.invoke.InvokerBytecodeGenerator$CpPatch
java.lang.invoke.LambdaFormBuffer
java.lang.invoke.LambdaFormEditor$Transform
java.lang.invoke.LambdaFormEditor
java.lang.invoke.DelegatingMethodHandle$Holder
java.lang.invoke.MethodHandleImpl$IntrinsicMethodHandle
java.lang.invoke.DelegatingMethodHandle
sun.invoke.util.Wrapper
java.lang.invoke.DirectMethodHandle$Accessor
java.lang.invoke.DirectMethodHandle
sun.invoke.empty.Empty
sun.invoke.util.VerifyType
java.lang.invoke.BoundMethodHandle$Species_L
java.lang.NoSuchFieldException
java.util.ImmutableCollections$ListItr
java.util.ListIterator
java.lang.invoke.SimpleMethodHandle
[Ljava.lang.invoke.BoundMethodHandle$SpeciesData;
[Ljava.lang.invoke.ClassSpecializer$SpeciesData;
java.lang.invoke.BoundMethodHandle$Specializer$Factory
java.lang.invoke.ClassSpecializer$Factory
java.util.ImmutableCollections$SubList
java.lang.invoke.BoundMethodHandle$SpeciesData
java.lang.invoke.ClassSpecializer$SpeciesData
java.lang.invoke.ClassSpecializer
java.util.function.Function
java.lang.invoke.BoundMethodHandle$Specializer
java.lang.invoke.ClassSpecializer
java.lang.invoke.BoundMethodHandle
java.lang.invoke.InnerClassLambdaMetafactory
[[I
java.lang.invoke.InnerClassLambdaMetafactory$ForwardingMethodGenerator
java.lang.invoke.TypeConvertingMethodAdapter
jdk.internal.org.objectweb.asm.AnnotationWriter
jdk.internal.org.objectweb.asm.AnnotationVisitor
jdk.internal.org.objectweb.asm.Frame
jdk.internal.org.objectweb.asm.Label
jdk.internal.org.objectweb.asm.MethodWriter
jdk.internal.org.objectweb.asm.MethodVisitor
[Ljava.util.concurrent.ConcurrentHashMap$CounterCell;
[Ljdk.internal.org.objectweb.asm.Item;
jdk.internal.org.objectweb.asm.Item
jdk.internal.org.objectweb.asm.ByteVector
jdk.internal.org.objectweb.asm.ClassWriter
jdk.internal.org.objectweb.asm.ClassVisitor
sun.invoke.util.BytecodeDescriptor
java.lang.invoke.InfoFromMemberName
java.lang.invoke.MethodHandleInfo
[Ljdk.internal.org.objectweb.asm.Type;
jdk.internal.org.objectweb.asm.Type
java.lang.invoke.InnerClassLambdaMetafactory
java.lang.invoke.AbstractValidatingLambdaMetafactory
java.lang.invoke.MethodHandleImpl
jdk.internal.misc.JavaLangInvokeAccess
java.lang.invoke.Invokers$Holder
java.lang.invoke.BootstrapMethodInvoker
java.util.function.Predicate
java.lang.WeakPairMap$Pair$Lookup
java.lang.WeakPairMap$Pair
java.lang.WeakPairMap
java.lang.Module$ReflectionData
java.lang.invoke.InvokerBytecodeGenerator
java.lang.invoke.InvokerBytecodeGenerator
[Ljava.lang.invoke.MethodHandleImpl$Intrinsic;
java.lang.invoke.MethodHandleImpl$Intrinsic
java.lang.invoke.LambdaForm$Holder
[[Ljava.lang.invoke.LambdaForm$Name;
[[Ljava.lang.Object;
[Ljava.lang.Cloneable;
[Ljava.lang.invoke.LambdaForm$Name;
java.lang.invoke.LambdaForm$Name
[Ljava.lang.invoke.LambdaForm$BasicType;
java.lang.invoke.LambdaForm$BasicType
java.lang.NoSuchMethodException
[Ljava.lang.invoke.LambdaForm$Kind;
java.lang.invoke.LambdaForm$Kind
java.lang.invoke.Invokers
java.lang.invoke.MethodHandleImpl
sun.invoke.util.ValueConversions
java.lang.invoke.DirectMethodHandle$Holder
[Ljava.lang.invoke.LambdaForm$NamedFunction;
java.lang.invoke.LambdaForm$NamedFunction
[Ljava.lang.invoke.LambdaForm;
[Lsun.invoke.util.Wrapper;
sun.invoke.util.Wrapper$Format
sun.invoke.util.Wrapper
sun.invoke.util.VerifyAccess
[Ljava.lang.invoke.MethodHandle;
java.lang.reflect.ReflectPermission
java.security.BasicPermission
java.security.Permission
java.security.Guard
java.lang.invoke.MemberName$Factory
java.lang.invoke.MethodHandles
[Ljava.lang.ref.SoftReference;
java.lang.invoke.MethodTypeForm
java.lang.Void
java.lang.invoke.MethodType$ConcurrentWeakInternSet$WeakEntry
[Ljava.lang.invoke.MethodType;
java.lang.invoke.MethodType$ConcurrentWeakInternSet
java.lang.invoke.MethodHandles$Lookup
java.lang.invoke.LambdaMetafactory
[Ljava.util.stream.StreamOpFlag;
jdk.internal.reflect.DelegatingMethodAccessorImpl
jdk.internal.reflect.NativeMethodAccessorImpl
[Ljava.lang.annotation.Annotation;
sun.reflect.annotation.AnnotationParser
java.util.HashMap$EntryIterator
java.util.HashMap$EntrySet
java.lang.Class
java.lang.PublicMethods$Key
java.lang.PublicMethods$MethodList
[Ljava.lang.reflect.Method;
java.util.EnumMap

... [Whosebug 不允许放这么多字符]

java.lang.invoke.MethodHandleNatives
java.lang.invoke.ResolvedMethodName
java.lang.invoke.MemberName
java.lang.invoke.VarHandle
java.lang.invoke.DirectMethodHandle
java.lang.invoke.MethodHandle
jdk.internal.reflect.CallerSensitive
java.lang.annotation.Annotation
jdk.internal.reflect.UnsafeStaticFieldAccessorImpl
jdk.internal.reflect.UnsafeFieldAccessorImpl
jdk.internal.reflect.FieldAccessorImpl
jdk.internal.reflect.FieldAccessor
jdk.internal.reflect.ConstantPool
jdk.internal.reflect.DelegatingClassLoader
jdk.internal.reflect.ConstructorAccessorImpl
jdk.internal.reflect.ConstructorAccessor
jdk.internal.reflect.MethodAccessorImpl
jdk.internal.reflect.MethodAccessor
jdk.internal.reflect.MagicAccessorImpl
java.lang.reflect.Constructor
java.lang.reflect.Method
java.lang.reflect.Executable
java.lang.reflect.Parameter
java.lang.reflect.Field
java.lang.reflect.Member
java.lang.reflect.AccessibleObject
java.lang.Module
java.util.Properties
java.util.Hashtable
java.util.Dictionary
java.util.Map
java.lang.ThreadGroup
java.lang.Thread$UncaughtExceptionHandler
java.lang.Thread
java.lang.Runnable
java.lang.ref.Finalizer
java.lang.ref.PhantomReference
java.lang.ref.FinalReference
java.lang.ref.WeakReference
java.lang.ref.SoftReference
java.lang.ref.Reference
java.lang.IllegalMonitorStateException
java.lang.WhosebugError
java.lang.OutOfMemoryError
java.lang.VirtualMachineError
java.lang.ArrayStoreException
java.lang.ClassCastException
java.lang.NoClassDefFoundError
java.lang.LinkageError
java.lang.ClassNotFoundException
java.lang.ReflectiveOperationException
java.security.SecureClassLoader
java.security.AccessControlContext
java.security.ProtectionDomain
java.lang.SecurityManager
java.lang.RuntimeException
java.lang.Exception
java.lang.ThreadDeath
java.lang.Error
java.lang.Throwable
java.lang.System
java.lang.ClassLoader
java.lang.Cloneable
java.lang.Class
java.lang.reflect.Type
java.lang.reflect.GenericDeclaration
java.lang.reflect.AnnotatedElement
java.lang.String
java.lang.CharSequence
java.lang.Comparable
java.io.Serializable
java.lang.Object
[J
[I
[S
[B
[D
[F
[C
[Z
Hello World!

有com.dvelopp.agenttest.Main,但没有com.dvelopp.agentconsumer.Test。为什么它会忽略我的应用程序的 class 路径?

premain方法先于main方法执行。顾名思义,数组中只包含加载的 classes。在执行代理的时间点,main class 还没有加载。