Created
May 1, 2014 23:16
-
-
Save skehlet/a1f521b95c4bbf49351c to your computer and use it in GitHub Desktop.
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.io.ByteArrayOutputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class ClassGenerator { | |
private List<Class<?>> classList = new ArrayList<>(); | |
public static void main(String[] args) { | |
new ClassGenerator().go(); | |
} | |
public void go() { | |
while(true) { | |
try { | |
Class.forName("ClassGenerator", true, createNewClassLoader()); | |
} catch (ClassNotFoundException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
private ClassLoader createNewClassLoader() { | |
return new ClassLoader() { | |
public Class<?> loadClass(String classNameWithPackage) throws ClassNotFoundException { | |
if(!classNameWithPackage.contains("ClassGenerator")) { | |
return super.loadClass(classNameWithPackage); | |
} | |
String className = classNameWithPackage.replace('.', '/') + ".class"; | |
byte[] classData = null; | |
InputStream inputStream = null; | |
try { | |
inputStream = getResourceAsStream(className); | |
byte[] buffer = new byte[1024]; | |
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); | |
int bytesRead = -1; | |
while ((bytesRead = inputStream.read(buffer)) != -1) { | |
outputStream.write(buffer, 0, bytesRead); | |
} | |
classData = outputStream.toByteArray(); | |
} | |
catch (IOException e) { | |
e.printStackTrace(); | |
} | |
finally { | |
if (inputStream != null) { | |
try { | |
inputStream.close(); | |
} catch (Exception e) {} | |
} | |
} | |
Class<?> c = defineClass(classNameWithPackage, classData, 0, classData.length); | |
resolveClass(c); | |
System.out.println("Steve I am loading another copy of Dummy class. Soon Permgen will fill."); | |
classList.add(c); | |
return c; | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment