Java class loads the specified class operation

This article mainly introduces the java custom ClassLoader to load the specified class file operation, which has a good reference value, and I hope it will be helpful to everyone. Let's follow the editor to take a look

You can customize a class loader by inheriting ClassLoader and overriding the findClass method. What is a class loader and the loading process and order of the class loader will be discussed next time. Here is a small demo

First define a class, such as MyTest, and compile it into a class file, and then put it under a specified folder. The last few layers of the folder are its package name. Here I put the compiled class in: /Users/allen/Desktop/cn/lijie/MyTest.class
Insert picture description here

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/](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;`

`}`

`}`

The main function of the test:

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();
    }
  }
}

Execute the main function and call the show method of the external class:

Insert picture description here

Supplement: java remote load class file
1. Create java file on win and compile

Insert picture description here

2. Upload to remote server

Insert picture description here

3. Preparation for writing java code
:
introducing the jar package ganymed-ssh2-262.jar

  • 1. To load an external class, define your own class loader

  • 2. Use memory streaming

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; 
 } 
}

Output result:
Insert picture description here

The above is personal experience, I hope to give you a reference, and I hope you can support the editor. If there are mistakes or not fully considered, please feel free to enlighten me.

Guess you like

Origin blog.csdn.net/dcj19980805/article/details/115247234