-1

I'm trying to load some java built-in classes like Object and Calendar

Class<?> proxied = new ByteBuddy()
                .subclass(Calendar.class)
                .method(ElementMatchers.not(ElementMatchers.isClone().or(ElementMatchers.isFinalizer()).or(ElementMatchers.isEquals()).or(ElementMatchers.isHashCode()).or(ElementMatchers.isToString())))
                .intercept(MethodDelegation.to(new MyMethodInterceptor()))
                .make()
                .load(Calendar.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
                .getLoaded();

When using Calendar.class.getClassLoader(), it will fail.

Caused by: java.lang.ClassNotFoundException: 
at net.bytebuddy.dynamic.loading.ByteArrayClassLoader.findClass(ByteArrayClassLoader.java:403)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
... 15 more

However, if I change the classLoader to ClassLoader.getSystemClassLoader() it works good. Here's a post I found SystemClassLoader vs obj.getClass.getClassLoader(). Can someone help explain the reason behind it?

zxzxzx
  • 1
  • 1
  • _"it will fail"_ - What is the error message (complete stack trace)? Please take the [tour], visit the [help] and read [Ask] to learn how to use this site effectively. – Jim Garrison Jun 07 '22 at 22:48

1 Answers1

0

The getClassLoader() method of java.lang.Class is specced to return null when that class was loaded by the system classloader. Why doesn't it return the ClassLoader instance representing the system loader? I'm sure there's a reason for it, but I'm not familiar with it. At any rate, that's how it works. (This also explains why it's MyClass.class.getResource and never MyClass.class.getClassLoader.getResource).

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72