java 사용자 정의 ClassLoader 지정 한 class 파일 불 러 오기 동작
5136 단어 자바ClassLoader로드class
먼저 MyTest 와 같은 클래스 를 정의 하고 class 파일 로 컴 파일 한 다음 에 지정 한 폴 더 아래 에 놓 습 니 다.그 중에서 폴 더 의 마지막 몇 층 은 가방 이름 입 니 다.여기 서 저 는 이 컴 파일 된 클래스 를/Users/allen/Desktop/cn/lijie/my Test.class 에 놓 겠 습 니 다.
package cn.lijie;
public class MyTest {
public void show() {
System.out.println("show test!");
}
}
사용자 정의 클래스 로 더:
public class MyClassLoader extends ClassLoader {
@Override
protected Class<?> findClass(String name) {
String myPath = "file:///Users/allen/Desktop/" + name.replace(".","/") + ".class";
System.out.println(myPath);
byte[] cLassBytes = null;
Path path = null;
try {
path = Paths.get(new URI(myPath));
cLassBytes = Files.readAllBytes(path);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
Class clazz = defineClass(name, cLassBytes, 0, cLassBytes.length);
return clazz;
}
}
테스트 의 주 함수:
public class MainClass {
public static void main(String[] args) throws ClassNotFoundException {
MyClassLoader loader = new MyClassLoader();
Class<?> aClass = loader.findClass("cn.lijie.MyTest");
try {
Object obj = aClass.newInstance();
Method method = aClass.getMethod("show");
method.invoke(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
}
주 함 수 를 실행 하고 외부 class 의 show 방법 을 호출 합 니 다:추가:자바 원 격 으로 class 파일 불 러 오기
1.win 에 자바 파일 을 만 들 고 컴 파일 하기
2.원 격 서버 에 업로드
3.자바 코드 작성
준비:
jar 패키지 ganymed-ssh 2-262.jar 도입
1.외부 클 라 스 를 불 러 오 려 면 클래스 로 더 를 정의 해 야 합 니 다.
2.메모리 스 트림 사용
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SFTPInputStream;
import ch.ethz.ssh2.SFTPv3Client;
public class Fs{
public static void main(String[] args) throws Exception {
OwnClassLoader ocl = new OwnClassLoader();
String ip,user,password;
ip = "120.34.168.80";// ip
user = "root";//username
password = "123456";//password
ocl.login(ip, user, password);
Object obj = ocl.loadeOthClass("/opt/4/tt.class");//class
System.out.println(obj);
Class c = obj.getClass();
Field f = c.getDeclaredField("age");
f.setAccessible(true);
System.out.println("age:"+f.get(obj));
}
}
//
class OwnClassLoader extends ClassLoader{
private Connection conn = null;
//
public Connection login(String ip,String user,String password){
Connection conn = null;
try {
// new Connection(ip, port) , 22
conn = new Connection(ip);
//
conn.connect();
//
conn.authenticateWithPassword(user, password);
this.conn = conn;
return conn;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//
public Object loadeOthClass(String url) throws Exception{
if(null==conn)
throw new Exception(" ");
SFTPv3Client sc = new SFTPv3Client(conn);// ssh
InputStream is = new SFTPInputStream(sc.openFileRO(url));//
byte[] b = this.readClassFile(is);
Class<?> c = super.defineClass(b, 0, b.length);// class
return c.newInstance();//
}
// class
private byte[] readClassFile(InputStream is){
byte[] b = new byte[1024];
int len;
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();//
while((len=is.read(b))!=-1){
bos.write(b, 0, len);
}
b = bos.toByteArray();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(is!=null)
is.close();
if(bos!=null)
bos.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
return b;
}
}
출력 결과:이상 은 개인 적 인 경험 이 므 로 여러분 에 게 참고 가 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.만약 잘못 이 있 거나 완전히 고려 하지 않 은 부분 이 있다 면 아낌없이 가르침 을 주시 기 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.