Last active
December 17, 2015 14:29
-
-
Save zhongl/5625338 to your computer and use it in GitHub Desktop.
`ClassNotFound` trap in using BTrace.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.Exception; | |
import java.lang.Object; | |
import java.lang.reflect.Method; | |
import java.io.ByteArrayOutputStream; | |
import java.io.InputStream; | |
/* | |
TODO: Btrace `jps | grep ClassNotFound | grep -oE '[0-9]+'` Script.java | |
import com.sun.btrace.annotations.*; | |
import com.sun.btrace.AnyType; | |
import static com.sun.btrace.BTraceUtils.*; | |
@BTrace | |
public class Script { | |
@OnMethod(clazz = "ClassNotFound$Bomb" , method = "tick") | |
public static void trace(@ProbeMethodName String pmn, AnyType[] args) { | |
print(pmn); | |
printArray(args); | |
} | |
} | |
*/ | |
public class ClassNotFound { | |
public static void main(String[] args) throws Exception{ | |
Object o = Class.forName("ClassNotFound$Bomb", false, new CustomizedClassLoader()).newInstance(); | |
final Method tick = o.getClass().getMethod("tick"); | |
while (true) { | |
tick.invoke(o); | |
try { | |
Thread.sleep(2000L); | |
} catch (Exception e) { | |
break; | |
} | |
} | |
} | |
public static class CustomizedClassLoader extends ClassLoader { | |
@Override | |
public Class<?> loadClass(String name) throws ClassNotFoundException { | |
Class<?> aClass = findLoadedClass(name); | |
if (aClass != null) return aClass; | |
if (name.startsWith("java") || name.startsWith("com.sun") || name.startsWith("sun")) { | |
return getParent().loadClass(name); | |
} else { | |
try { | |
InputStream inputStream = getResourceAsStream(name + ".class"); | |
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); | |
int read = 0; | |
while ((read = inputStream.read()) > -1) outputStream.write(read); | |
byte[] bytes = outputStream.toByteArray(); | |
return defineClass(name, bytes, 0, bytes.length); | |
} catch (Exception e) { | |
throw new ClassNotFoundException(name, e); | |
} | |
} | |
} | |
@Override | |
public String toString() { | |
return "CustomizedClassLoader"; | |
} | |
} | |
public static class Bomb { | |
public void tick() { | |
System.out.println("tick!"); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment