反射机制详解

import java.lang.reflect.Method;

public class TestReflection {
	public static void main(String[] args) throws Exception {
	String str = "Other";
	Class c=Class.forName("com.yangfan.反射.Other");
	Object object = c.newInstance();
	System.out.println(object);
	Method[] method = c.getMethods();
	for(Method m:method){
		if (m.getName().equals("Imple")) {
			System.out.println("被调用方法名称:"+m.getName());
			m.invoke(object, 1001,1002);//这是一个可变参数!
		}
		
	}
	}
}
/*
Other.clas is loaded!
Other is inting
com.yangfan.反射.Other@c17164
被调用方法名称:Imple
我是Imple方法!传入参数为:1001
2003

 */

 class Other{
	 
	 static{
		 System.out.println("Other.clas is loaded!");
	 }
	 public Other(){
		 System.out.println("Other is inting");
	 }
	 public void Imple(int i,int j){
		 System.out.println("我是Imple方法!传入参数为:"+i);
		 int k=i+j;
		 System.out.println(k);
	 }
	 
 }


1.学习反射前先了解classloader,下面这些是jdk已有的classloader ,其中bootstrap是c写的,最先启动加载java核心类的classloader 如String类

 

2.jdk classloader的层次关系,注意这是对象这间的关系,不是类的继承关系,对象间的子对象有指向父对象的引用,

  

用一个小的while可以得出所有的classloader

public class ClassLoaderTest {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//System.out.println(ClassLoaderTest.class.getClassLoader().getClass().getName());
		ClassLoader c = ClassLoaderTest.class.getClassLoader();
		while (c!=null) {
			System.out.println(c.getClass().getName());
			c = c.getParent();
		}
	}
	结果:sun.misc.Launcher$AppClassLoader
              sun.misc.Launcher$ExtClassLoader

}


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值