1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| class ClassLoaderFrame extends JFrame
{
//partie affichage
public ClassLoaderFrame()
{
setTitle("ClassLoaderTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setLayout(new GridLayout(3,2));
add(new JLabel("class"));
add(nameField);
add(new JLabel("Clé"));
add(keyField);
JButton loadButton = new JButton("Charger");
add(loadButton);
loadButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
runClass(nameField.getText(), keyField.getText());
}
});
pack();
}
public void runClass(String name, String key)
{
try{
ClassLoader loader = new CryptoClassLoader(Integer.parseInt(key));
System.out.println("runClass1");
Class c = loader.loadClass(name);
System.out.println("runClass2");
String[] args = new String[] {};
Method m = c.getMethod("main", args.getClass());
System.out.println("runClass3");
m.invoke(null, (Object) args);
System.out.println("runClass4");
}
catch(Throwable e)
{
JOptionPane.showMessageDialog(this,e);
}
}
private JTextField keyField = new JTextField("3", 4);
private JTextField nameField = new JTextField(30);
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
}
class CryptoClassLoader extends ClassLoader
{
public CryptoClassLoader(int k)
{key = k;}
protected Class findClass(String name) throws ClassNotFoundException
{
byte[] classBytes = null;
try{
classBytes = loadClassBytes(name);
System.out.println("classBytes = "+classBytes);
}
catch(IOException e)
{
System.out.println("findClass1");
throw new ClassNotFoundException(name+" findClass1");
//System.out.println("findClass1");
}
System.out.println("findClass11");
Class cl = defineClass(name, classBytes, 0, classBytes.length);
System.out.println("findClass12");
if(cl == null)
{
System.out.println("findClass2");
throw new ClassNotFoundException(name+" findClass2");
}
System.out.println("findClass3");
return cl;
}
private byte[] loadClassBytes(String name) throws IOException
{
System.out.println(name);
String cname = name.replace('.', '/')+".eee";
System.out.println(cname);
FileInputStream in = null;
in = new FileInputStream(new File(cname));
System.out.println("in = "+in);
try{
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int ch;
System.out.println("in1");
while((ch = in.read()) !=-1)//out1
{
byte b = (byte) (ch);
buffer.write(b);
}
System.out.println("in2");
in.close();
System.out.println("in2");
return buffer.toByteArray();
}
finally
{
in.close();
System.out.println("in3");
}
}
private int key;
} |
Partager