이 기사는 주로 JAR 및 클래스 파일의 Java 동적로드의 관련 내용을 다음과 같이 연구합니다.
자바로로드되는 클래스 파일은 역동적입니다. 다시 말해, 우리는 그것을 사용할 때만로드 할 것이며, 그것을 사용하지 않으면 우리는 수업을로드하지 않을 것입니다.
Java는 우리에게 두 가지 동적 메커니즘을 제공합니다. 첫 번째는 암시 적 메커니즘입니다. 두 번째는 디스플레이 메커니즘입니다. 다음과 같이 :
두 가지 방법 :
class.forname () 메소드에는 두 가지 형식이 있습니다.
public static Class forName(String className)public static Class forName(String className, boolean initialize,ClassLoader loader) 매개 변수가 하나만있는 Forname () 메소드를 호출하는 것은 class.forname (classname, true, loader)과 동일합니다.
두 가지 메소드 모두 끝에 기본 메소드 Forname0 ()에 연결되어야합니다.
3 개의 매개 변수가있는 Forname ()은 마지막 호출은 다음과 같습니다. Forname0 (이름, 초기화, 로더);
새로운 클래스를 인스턴스화하기 위해 새로운 사용을 사용하든 클래스 .forname () 메소드를 하나의 매개 변수 만 사용하든 "클래스 + 정적 코드 블록 실행을로드하는 단계"가 내부에 암시됩니다.
세 가지 매개 변수가있는 class.forname () 메소드를 사용하는 경우, 두 번째 매개 변수가 False 인 경우 클래스 로더는 클래스 만로드하고 정적 코드 블록을 초기화하지 않습니다. 클래스가 인스턴스화 된 경우에만 정적 코드 블록이 초기화됩니다. 정적 코드 블록은 클래스가 처음으로 인스턴스화 될 때 초기화됩니다.
클래스 로더는 클래스를로드하는 데 사용됩니다. 클래스가로드되면이 클래스에서 참조 된 모든 클래스도로드 되며이 로딩도 재귀 적입니다. 즉, A가 B를 참조하고 B가 C를 지칭하면 A가로드되면 B도로드되고 B도로드되고 B가로드되면 C도로드됩니다. 필요한 모든 클래스가 잘로드 될 때까지 재귀 적입니다.
package com.demo.test; import java.io.bytearrayoutputStream; import java.io.file; import java.io.fileInputStream; import java.io.filenotfoundException; import java.io.ioexception; import java.lang.reflct.field; lemport java.rang.langectece java.lang.reflect.method; import java.net.malformedurlexcept; import java.net.url; import java.net.urlclassloader; public class dynamicloaddemo {enum filetype {jar, class, 기타} 정적 클래스 myclassloader inclass classends classness (strows) filenotFoundException {class <?> cls = findloadedClass (name); if (cls! = null) {return cls;} fileInputStream fis = new FileInputStream (file); byTearRayOutputes Baos = new ByTearRayOutputStream (); byte [] bucter = new Byte [1024]; int len; int Len; fis.read (buffer); if (len == -1) {break;} baos.write (buffer, 0, len);} // fileInputStream의 Flush는 빈 작업입니다. 플러시는 캐시에 물건을 엔터티 (하드 디스크 또는 네트워크 스트림)에 쓰는 기능이기 때문입니다. 여기에는 필요하지 않으므로 비어 있습니다. //baos.flush (); byte [] data = baos.tobytearray (); return defineclass (null, data, 0, data.length);} catch (ioexception e) {e.printstacktrace ();} 최종적 {try {baos.close ();} catch (ioxception e) {e.printstacktrace ();}}. {fis.close ();} catch (ioexception e) {e.printstacktrace ();}} return null;}} public static void main (string [] args) {String classname = "com.demo.test.helloworld"; String Paths [] = helloworld.jar " paths) {string lowerpath = path.tolowercase (); filetype filetype = filetype.other; if (hellepath.endswith ( ". jar") || hellepath.endswith ( ". zip")) {filetype = filetype.jar;} else (lowerpath.endswith ( ". class"))} if (filetype. if (filetype)}} fileType.other) {return;} file file = 새 파일 (path); if (! file.exists ()) {return;} try {url url = file.touri (). tourl (); system.out.println (url.toString ()); class <?> cls = null; null (filetype) {new urly jar : urlclasser. url [] {url}, orl.currentthread (). getContextClassLoader ()); cls = classloader.loadClass (className); break; case class : myClassLoader myClassLoader = new MyClassLoader (); cls = myClassLoader.loadClass (className, 파일); break;} if (rem;} if;} if). {return;} // 인스턴스 변수 필드 필드 = cls.getDeclaredfield ( "hello"); if (! field.isaccessible ()) {field.setAccessible (true);} system.out.println (field.get (cls.get ())); // 매개 변수 정적 메소드 메소드 메소드 메소드 메소드 메소드 메소드를 호출하십시오. cls.getDeclaredMethod ( "saystatichello", null); if (! staticMethod.isaccessible ()) {staticMethod.setAccessible (true);} // 함수의 반환 값이 무효 인 경우, nullstaticmethod.invoke (cls, null); // 인스턴스 메소드 메소드 방법 = cls.getDecLaredDod ( "say", string.class); {method.setAccessible (true);} 객체 ret = method.invoke (cls.newinstance (), "hello world"); system.out.println (ret);} catch (marformedurlexception e) {e.printstacktrace ();} catch (classnotfoundexception e) {e.printstacktrace ();} (noSuchecection); {e.printstacktrace ();} catch (securityException e) {e.printstacktrace ();} catch (불법 행위 exception e) {e.printstacktrace ();} catch (e.printstacktrace ();} catch (e.procttargetexcemption e) {e.procttacttrace (e.procttargetexception e) {e.printtacktrace e) (InstantiationException e) {e.printstacktrace ();} catch (nosuchfieldexception e) {e.printstacktrace ();} catch (filenotfoundException e) {e.printstacktrace ();}}}}결과:
위는 Java Dynamic Loading Jar 및 클래스 파일 인스턴스 분석에 대한이 기사의 모든 내용입니다. 모든 사람에게 도움이되기를 바랍니다. 관심있는 친구는이 사이트의 다른 관련 주제를 계속 참조 할 수 있습니다. 단점이 있으면 메시지를 남겨 두십시오. 이 사이트를 지원해 주신 친구들에게 감사드립니다!