java 사용자 정의 ClassLoader 지정 한 class 파일 불 러 오기 동작

ClassLoader 를 계승 하고 findClass 방법 을 다시 쓰 면 클래스 로 더 를 사용자 정의 할 수 있 습 니 다.구체 적 으로 클래스 로 더 와 클래스 로 더 의 로 딩 과정 과 순 서 는 다음 에 말씀 드 리 겠 습 니 다.다음은 작은 demo 를 드 리 겠 습 니 다.
먼저 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; 
 } 
}
출력 결과:

이상 은 개인 적 인 경험 이 므 로 여러분 에 게 참고 가 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.만약 잘못 이 있 거나 완전히 고려 하지 않 은 부분 이 있다 면 아낌없이 가르침 을 주시 기 바 랍 니 다.

좋은 웹페이지 즐겨찾기