Java鍙嶅皠鏈哄埗
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java鍙嶅皠鏈哄埗相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/print' title='print'>print
class instance row target author failed vat access鑳屾櫙鐭ヨ瘑
- Class绫伙紙鍙嶅皠鏈哄埗瀹炵幇鐨勫熀纭€锛?/li>
銆€銆€ Java涓殑Class鐨勭被鏄竴涓壒娈婄殑绫伙紝JVM鍔犺浇瀛楄妭鐮佹枃浠剁殑鏃跺€欙紝鍦ㄦ柟娉曞尯涓负姣忎竴涓被鍒涘缓涓€涓搴旂殑Class绫诲璞★紝杩欎釜瀵硅薄涓寘鍚被鐨勪俊鎭細鏂规硶锛屽瓧娈碉紝娉ㄨВ绛夈€?/p>
鏄粈涔?/strong> 缂栫▼瀹炰緥锛屼唬鐮佷腑浼氬寘鍚互涓嬪嚑涓儴鍒嗙殑瀹炵幇銆?/strong> 棣栧厛锛屽厛瀹氫箟涓€涓敤浜庡弽灏勭殑绫?/p>
鐒跺悗鎴戜滑閫氳繃main鏂规硶绫昏繘琛屽弽灏勬満鍒剁殑瀹炵幇package priv.darrenqiao.reflection;
銆€銆€鍙互鍦ㄨ繍琛屾椂鍔ㄦ€佺殑鑾峰彇绫荤殑淇℃伅銆傦紙姣斿锛氱被閲岄潰瀹氫箟鐨勬柟娉曪紝瀛楁锛屾敞瑙g瓑淇℃伅锛?/p>
鏈変粈涔堢敤
銆€銆€鍙互鎻愰珮绋嬪簭鐨勫彲鎵╁睍鎬э紝浠ュ墠娌℃柊澧炲姞涓€涓被灏遍渶瑕佷慨鏀瑰師鏉ョ殑绋嬪簭锛屼互鍏煎鏂扮殑绫伙紝鐜板湪鍙渶瑕侀€氳繃鍙嶅皠灏辫兘澶熻幏鍙栧埌鏂板鐨勮嚜瀹氫箟绫讳俊鎭紝涓嶉渶瑕佹瘡娆′慨鏀瑰師鏉ョ殑绋嬪簭銆?/p>
package priv.darrenqiao.reflection;
/*
* @Author : darrenqiao
* */
public class ReflectionClass {
public String name;
public Integer age;
private String result;
public void testName() {
}
public ReflectionClass(String result) {
super();
this.result = result;
}
public void show(String test) {
System.out.println("show result " + this.result + " and " + test);
}
public void testAge() {
}
}
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/*
* @Author : darrenqiao
* */
public class Main {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
銆€銆€銆€銆€銆€//鑾峰彇绫?/span>鏂规硶涓€
ReflectionClass reflection = new ReflectionClass("success");
Class<?> classInfoForReflection = reflection.getClass();
//鑾峰彇绫?/span>鏂规硶浜? //Class<ReflectionClass> classInfoForReflection = ReflectionClass.class;
//鑾峰彇绫?/span>鏂规硶涓夛紝姣旇緝甯哥敤鐨勬槸杩欑锛屽洜涓哄悗闈㈢殑绫诲叏璺緞鍙互浣滀负閰嶇疆椤规斁鍒伴厤缃枃浠朵腑鍔ㄦ€佺殑鑾峰彇
//Class<?> classInfoForReflection = Class.forName("priv.darrenqiao.reflection.ReflectionClass");
Method[] methods = classInfoForReflection.getMethods();
System.out.println("methods for class classInfoForReflection is");
for (Method m : methods) {
System.out.println(m.getName());
}
//閫氳繃鏋勯€犲嚱鏁颁紶鍙傛暟
Class<ReflectionClass> classInfoForReflectionClass = ReflectionClass.class;
Constructor<?> c = classInfoForReflectionClass.getConstructor(String.class);
Object reflectionObject = (Object) c.newInstance("failed");
//鎵ц鎸囧畾鍑芥暟
Method method = classInfoForReflectionClass.getMethod("show", String.class);
method.invoke(reflectionObject, "test final");
}
}
以上是关于Java鍙嶅皠鏈哄埗的主要内容,如果未能解决你的问题,请参考以下文章