자바 반사 소개 의 2---해부 구조 기

2994 단어 자바C++cC#Gmail

              ,  :    ,  ,     。       ,            。                。
        :         Java Student ,    cn.csdn.reflect          class  .                   :

   //  :     Student         ?    :
	@Test
	public void test3()throws Exception{
		//1、    ("cn.csdn.reflect.Student"      )
		Class cls = Class.forName("cn.csdn.reflect.Student");
		//2、             
		Constructor csr[] = cls.getConstructors();
		//3、     csr
		for(Constructor c:csr){
			//                 
			 System.out.println(c.toGenericString());
			
	}


//   :public Student()   
	@Test
	public void test1() throws Exception{
		// 1、      ("cn.csdn.reflect.Student"      )
		Class cls = Class.forName("cn.csdn.reflect.Student");
		// 2、           
		Constructor constructor = cls.getConstructor(null);
		// 3、      
		Student entity = (Student) constructor.newInstance(null);
        //4、       
		entity.study();
	}
	
	//  :public Student(String name,int age);   
	@Test
	public void test2()throws Exception{
		//1、    ("cn.csdn.reflect.Student"      )
		Class cls = Class.forName("cn.csdn.reflect.Student");
		//2、            
		Constructor constructor = cls.getConstructor(String.class,int.class);
		//3、     
		Student entity = (Student)constructor.newInstance("redarmy",90);
		//4、    
		entity.study();
		System.out.println(entity.getName());
	}
	
	
     //  :public cn.csdn.reflect.Student(java.lang.String[])   
	@Test
	public void test4()throws Exception{
		//1、   
		Class cls = Class.forName("cn.csdn.reflect.Student");
		//2、                       
		Constructor csr = cls.getConstructor(String[].class);
		
		String str[]={"111","123"};
		//3、      
		Student entity = (Student)csr.newInstance((Object)str);
/*          :Java   java.lang.IllegalArgumentException: wrong number of arguments   */
[url]http://redarmychen.iteye.com/blog/924134
[/url]
		//4、    
		entity.study();
	}

//   private Student(List list)   
	@Test
	public void test5()throws Exception{
		//1、   
		Class cls = Class.forName("cn.csdn.reflect.Student");
		//2、                       
		Constructor csr = cls.getDeclaredConstructor(List.class);
                 //      private      
		csr.setAccessible(true);//    private      
		//3、      
		Student entity = (Student)csr.newInstance(new ArrayList());
		//4、    
		entity.study();
	}


       redarmy_chen  ,   redarmy_chen                    [email protected] 


좋은 웹페이지 즐겨찾기