Carga de clases

elminotopo
07 de Abril del 2006
Hola a todos.
Hay forma de que un programa en java ejecutandose busque clases externas y las levante para usarlas.
Mi idea es hacer un programa "upgradeable" que busque clases nuevas en un disco por ejemplo y genere los onjetos para usarlos en tiempo de ejecucion.

mak
07 de Abril del 2006
Igual esto te puede dar alguna pista para lo que quieres hacer:


package uploading;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Loader extends ClassLoader {

private static final String FS = System.getProperty("file.separator");

public Class loadClassFromFile(String className, File classFile) {

if (this.isValidClassFilePath(classFile)) {
try {
DataInputStream is = new DataInputStream(new FileInputStream(
classFile));
int l = is.available();
byte[] byteCode = new byte[l];
is.readFully(byteCode);
return this.defineClass(className, byteCode, 0, l);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

public static void main(String[] args) {
String className = "staticTest.TestFrame";
String classFilePath = "C:\Documents and Settings\kmakibar\workspace\JavaTests\bin\staticTest\TestFrame.class";
Loader loader = new Loader();
File classFile = new File(classFilePath);
Class loadedClass = loader.loadClassFromFile(className, classFile);
if (loadedClass != null) {
int classModifier = loadedClass.getModifiers();
System.out.println(Modifier.toString(classModifier) + " "
+ loadedClass.getName());

System.out.println();

System.out.println("FIELDS:");
Field[] fields = loadedClass.getDeclaredFields();
for (Field field : fields) {
int fieldModifier = field.getModifiers();
System.out.println(Modifier.toString(fieldModifier) + " "
+ field.getType() + " " + field.getName());
}
System.out.println();
System.out.println("METHODS:");
Method[] methods = loadedClass.getDeclaredMethods();
for (Method method : methods) {
int methodModifier = method.getModifiers();
System.out.print(Modifier.toString(methodModifier) + " "
+ method.getReturnType().getSimpleName() + " "
+ method.getName() + "(");
Class[] parTypes = method.getParameterTypes();
if (parTypes.length > 0) {
System.out.print(parTypes[0].getSimpleName());
for (int i = 1; i < parTypes.length; i++) {
System.out.print("," + parTypes[i].getSimpleName());
}
}
System.out.println(")");
}
System.out.println();
}
}

private boolean isValidClassFilePath(File classFile) {
if (classFile.isFile()) {
String path = classFile.getAbsolutePath();
int bi = path.lastIndexOf(FS);
int ei;
if (bi > 0) {
ei = path.lastIndexOf(".class");
if (ei > bi) {
return true;
}
}
}
return false;
}
}