Java程序的工作機制
Java虛擬機查找這些java對象
java虛擬機根據class path來查找java對象
bootstrap
extension: java
application: java
三個class path各有對應的classloader
當程序中調用new指令
Java虛擬機加載這些java對象
每個java虛擬機都在其啟動時產生一個唯一的class heap
反射
JVM對反射的處理
簡單例子代碼
import java
import java
import java
import java
public class
public static void main(String[] args){
TempImpl t
try {
Method t
t
} catch (NoSuchMethodException e) {
e
} catch (IllegalAccessException e) {
e
} catch (InvocationTargetException e) {
e
}
try {
System
} catch (IOException e) {
e
}
}
}
復雜例子代碼
import java
import java
import java
import java
public class
public static void main(String[] args){
TempImpl t
TempImpl t
Temp
try {
Method t
Method t
t
t
if(t
System
}
else{
System
}
if(t
System
}
else{
System
}
t
} catch (NoSuchMethodException e) {
e
} catch (IllegalAccessException e) {
e
} catch (InvocationTargetException e) {
e
}
try {
System
} catch (IOException e) {
e
}
}
}
分析
動態代理
Sun對動態代理的說明
一個簡單例子代碼
動態代理的內部實現——代碼生成
研究JDK源代碼
public class ProxyClassFile{
public static void main(String[] args){
String proxyName =
TempImpl t = new TempImpl(
Class[] interfaces =t
byte[] proxyClassFile = ProxyGenerator
proxyName
File f = new File(
try {
FileOutputStream fos = new FileOutputStream(f);
fos
fos
fos
} catch (FileNotFoundException e) {
e
} catch (IOException e) {
e
}
}
}
運行該類
public interface Temp{
public void Talk();
public void Run();
}
import java
public final class TempProxy extends Proxy
implements Temp{
private static Method m
private static Method m
private static Method m
private static Method m
private static Method m
public TempProxy(InvocationHandler invocationhandler) {
super(invocationhandler);
}
public final void Run() {
try {
h
return;
}
catch(Error _ex) { }
catch(Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final String toString(){
try{
return (String)h
}
catch(Error _ex) { }
catch(Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
return
}
public final int hashCode() {
try {
return ((Integer)h
}
catch(Error _ex) { }
catch(Throwable throwable){
throw new UndeclaredThrowableException(throwable);
}
return
}
public final void Talk(){
try{
h
return;
}
catch(Error _ex) { }
catch(Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
}
public final boolean equals(Object obj) {
try {
return ((Boolean)h
obj
}))
}
catch(Error _ex) { }
catch(Throwable throwable) {
throw new UndeclaredThrowableException(throwable);
}
return false;
}
static{
try{
m
m
m
m
m
Class
});
}
catch(NoSuchMethodException nosuchmethodexception) {
throw new NoSuchMethodError(nosuchmethodexception
}
catch(ClassNotFoundException classnotfoundexception) {
throw new NoClassDefFoundError(classnotfoundexception
}
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25693.html