Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class JavaCompiler {
- String name;
- ArrayList<?> data = new ArrayList();
- int constantPoolEnd;
- public static JavaCompiler getCompiler (String s, Package p) {
- JavaCompiler returnCompiler;
- try {
- new SecurityManager.checkCreateClassLoader();
- returnCompiler = new JavaCompiler(s, p);
- } catch (SecurityException se) {
- returnCompiler = null;
- } finally {
- return returnCompiler;
- }
- }
- JavaCompiler (String s, Package p) {
- String packageName = p.getName().replace(".", "/").concat("/").concat(s);
- //Add "magic"
- data.add(0xCAFEBABE);
- //Add the version number, minor number first, then major number
- data.add((short) 0); data.add((short) 61);
- //Add the constant pool
- data.add((short) 4);
- data.add((byte) 7); data.add((short) 1);
- data.add((byte) 1); data.add((short) packageName.length()); data.add(packageName);
- data.add((byte) 7); data.add((short) 3);
- data.add((byte) 1); data.add((short) 16); data.add("java/lang/Object");
- //Mark the end of the constant pool
- constantPoolEnd = 14;
- //Add access flags
- data.add(JavaCompiler.getDefaultAccessFlags.bytes()[0]); data.add(JavaCompiler.getDefaultAccessFlags.bytes()[1]);
- //Add this class and super class
- data.add((short) 0); data.add((short) 2);
- //Add interfaces
- data.add((short) 0);
- //Add fields
- data.add((short) 0);
- //Add methods
- data.add((short) 0);
- //Add attributes
- data.add((short) 0);
- this.name = name;
- }
- public void setAccessFlags (AccessFlags af) {
- }
- public Class<?> build () {
- ArrayList<byte> classData = new ArrayList();
- for (Object o : data) {
- if (o instanceof byte) {
- classData.add(o);
- } else if (o instanceof short) {
- classData.add(java.nio.ByteBuffer.allocate(2).putShort(o).array());
- } else if (o instanceof int) {
- classData.add(java.nio.ByteBuffer.allocate(4).putInt(o).array());
- } else if (o instanceof long) {
- classData.add(java.nio.ByteBuffer.allocate(8).putLong(o).array());
- } else if (o instanceof String) {
- classData.add(java.nio.ByteBuffer.allocate(o.length()).putInt(o).array());
- } else {
- throw new IllegalStateException("Class object is not a number or string.");
- }
- }
- return ClassLoader.geSystemClassLoader().defineClass(name, classData, 0, classData.length);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement