在java
中,所有的类都是通过类加载器所加载的,除根类加载器(bootstrap
)外,扩展类加载器和应用类加载器都是ClassLoader
的子类。下面是一个自定义ClassLoader
类,从网络中加载Class文件的一个简单的例子
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
public class MyClassLoader extends ClassLoader {
private String url;
public MyClassLoader(String url) {
this.url = url;
}
public MyClassLoader(ClassLoader parent, String url) {
super(parent);
this.url = url;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] classData = loadClassData(name);
return defineClass(name, classData, 0, classData.length);
}
private byte[] loadClassData(String name) throws ClassNotFoundException {
String uri = url + name;
return loadDataFromUrl(uri);
}
private byte[] loadDataFromUrl(String uri) throws ClassNotFoundException {
try {
URL url = new URL(uri);
InputStream inputStream = url.openStream();
byte[] b = new byte[1024];
int len;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(b)) != -1) {
bos.write(b, 0, len);
}
byte[] classData = bos.toByteArray();
return classData;
} catch (Exception ex) {
throw new ClassNotFoundException();
}
}
}
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) {
String url = "https://raw.githubusercontent.com/zjbshk/zjbshk.github.io/master/";
MyClassLoader myClassLoader = new MyClassLoader(url);
try {
Class<?> aClass = myClassLoader.loadClass("Student");
Object o = aClass.newInstance();
Field[] declaredFields = aClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
Object o1 = declaredField.get(o);
System.out.println(o1);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
public class Student {
private int age = 21;
private String name = "zjb";
private boolean sex = true;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
}
网友评论