220 var classBytes = cv.toByteArray();
221
222 Class<?> cls = new ClassLoader() {
223 public Class<?> defineClass() {224 return defineClass("Target", classBytes, 0, classBytes.length);225 }226 }.defineClass();
227
228 var interceptedTarget = Interceptor.create(cls, new Class[]{}, new Object[]{}, methodInterceptor);
149 var classBytes = cv.toByteArray();
150
151 Class<?> cls = new ClassLoader(superClass.getClassLoader()) {
152 public Class<?> defineClass() {153 return defineClass(className, classBytes, 0, classBytes.length);154 }155 }.defineClass();
156 Object instance;
157 try {
A non-overridden method is defined within an anonymous class, which is not used within that class at all.
Such a method cannot be called outside of the anonymous class in most cases, meaning it is a useless declaration.
Because anonymous classes have no names, there is no way at runtime for code outside an anonymous class to resolve any methods declared within them. The only way for an anonymous class to be interacted with by any other object is to override methods that exist in the parent class/interface(s) of the anonymous class.
Do note that there are still a number of ways to access such methods, through reflection, and other tricks.
Object anon = new Runnable() {
@Override
public void run() {
// ...
}
// This method my be public, but it can't be called from outside.
public void thing() {
System.out.println("thing");
}
}
anon.thing(); // This won't compile!
If you wish to create new methods to be called by external code, consider creating a proper class, or an inner (static) class that can have new methods.
class CustomRunnable extends Runnable {
@Override
public void run() {
// ...
}
public void thing() {
System.out.println("thing");
}
}
CustomRunnable cr = new CustomRunnable();
cr.thing(); // this works!