java.lang.Class: 반사 소스입니다.

15470 단어
1. 반사 개술
1. java.lang.Class: 반사 소스입니다.
우리는 컴파일을 통해 대응하는 클래스를 만듭니다.calss 파일 다음에 java를 사용합니다.exe 불러오기 (jvm의 클래스 불러오기) 여기 있습니다.class 파일.class 파일을 메모리에 불러오면 실행 시 클래스입니다. 캐시 영역이 존재합니다. 이 실행 시 클래스 자체는class의 실례입니다.
  • 실행 시 클래스마다 한 번만 불러오기
  • Class 인스턴스가 있는 후에야 다음과 같은 작업을 수행할 수 있습니다.
  • 대응하는 실행 시간 클래스를 만드는 대상(중점)
  • 대상의 운행시 클래스의 완전한 구조(속성, 방법, 구조기, 내부클래스,,,)를 얻을 수 있다(이해)
  • 대응하는 운행시류의 지정된 구조(속성, 방법)(중점)
  • 호출

    반사하기 전에, 어떻게 클래스의 대상을 만들고, 그 중의 방법 속성을 호출합니까
    public void test1() {
    		Person p = new Person();
    		p.setAge(10);
    		p.setName("AA");
    		p.show();
    		System.out.println(p);
    	}
    
    

    반사가 있으면 반사를 통해 하나의 종류의 대상을 만들고 그 중의 방법을 호출할 수 있다. 다음은 상세하게 설명한다.
    public void test2(www.lanboyulezc.cn ) throws Exception {
    		
    		Class clazz www.shentuylgw.cn= Person.class;
    		
    		//1.  clazz       Person    
    		Person p = (Person)clazz.newInstance();
    		System.out.println(p);
    		
    		//2.               ,public name     
    		Field f1 = clazz.getField("name");
    		f1.set(p, www.shentuylgw.cn"LiuDaHua");
    		System.out.println(p);
    		
    		//private age   
    		Field f2 = clazz.getDeclaredField("age");
    		f2.setAccessible(true);
    		f2.set(p, 20);
    		System.out.println(p);
    		
    		//3.                public   
    		Method m1 = clazz.getMethod("show");
        	//   
    		m1.invoke(p);
        	//       
    		Method m2 = clazz.getMethod("display", String.class);
    		m2.invoke(p, "www.jintianxuesha.com");
    		
    	}
    	
    

     
    2. Class의 실례를 어떻게 얻는가
    1. 실행 시 클래스 자체를 호출합니다.class 속성
    Class clazz = Person.class;
    System.out.println(clazz.getName());
    		
    Class clazz1 = String.class;
    System.out.println(clazz1.getName());
    
    

    2. 런타임 클래스의 대상을 통해 획득
    Person p = new Person();
    Class clazz2 = p.getClass();
    System.out.println(clazz.getName());
    
    

    3. Class의 정적 방법으로 획득하고 이를 통해 반사의 동태성을 체득한다
    String className = "com.atguigu.java.Person";
    		
    Class clazz4 = Class.forName(className);	   
    System.out.println(clazz4);
    
    
    

    4. 클래스를 통과하는 마운트
    ClassLoader classLoader = this.getClass().getClassLoader();
    Class clazz5 = classLoader.loadClass(className);
    System.out.println(clazz5.getName());
    

    전체 코드
    public void test4() throws Exception {
    		//1.         .class  
    		Class clazz = Person.class;
    		System.out.println(clazz.getName());
    		
    		Class clazz1 = String.class;
    		System.out.println(clazz1.getName());
    		
    		//2.           
    		Person p = new Person(www.chuancenpt.com);
    		Class clazz2 = p.getClass();
    		System.out.println(clazz.getName(www.tengyao3zc.cn));
    		
    		//3.  Class       ,     ,        
    		String className = "com.atguigu.java.Person";
    		
    		Class clazz4 = Class.forName(className);
    		System.out.println(clazz4);
    		
    		
    		//4.       
    		ClassLoader classLoader =www.jujinyule.com this.getClass().getClassLoader();
    		Class clazz5 =www.xingyunylpt.com classLoader.loadClass(className);
    		System.out.println(clazz5.getName());
    	}
    	
    
    

    정상으로 돌아오다
    3. 런타임 클래스 개체 만들기
    1. Class의 인스턴스 가져오기
    보통 클래스 이름을 직접 사용합니다.class, 예를 들면 Person.class
    당연하지, 위의 몇 가지 방법은 모두 가능하다
    String className = "com.atguigu.java.Person";
    Class clazz = Class.forName(className);
    

    2. 런타임 클래스 객체 만들기
    대응하는 실행 클래스의 대상을 만듭니다. newInstance () 를 사용합니다. 실제로는 실행 클래스의 빈 파라미터를 사용한 구조기입니다.
    성공적으로 만들려면
  • 대응하는 운행 시류에 빈 파라미터가 있어야 하는 구조기
  • 구조기의 권한 수식자의 권한은 충분해야 한다
  • Object obj = clazz.newInstance();//         
    Person p = (Person)obj;
    System.out.println(p);
    
    

    모든 코드
    public void test1(www.mLgjzc.cn) throws Exception {
    	//   Class  
       		Class clazz www.feihongyul.cn= Person.class;
    		
    		//            ,    newInstance(),                    
    		//        ,①                  ,②               
    		Object obj www.youy2zhuce.cn= clazz.newInstance();//         
    		Person p = (Person)obj;
    		System.out.println(p);		
    	}
    

    정상으로 돌아오다
    4. 반사를 통해 클래스의 완전한 구조를 얻는다.
    1. 런타임 클래스의 속성 가져오기
    1.getFields () 반환: 공통 필드를 나타내는 Field 대상의 그룹입니다. 실행 시 클래스와 부모 클래스에서public로 명시된 속성만 가져올 수 있습니다.
    Field[] fiels = clazz.getFields();
    for(int i=0;i

    2. getDeclaredFields (): 실행할 때 클래스 자체가 설명하는 모든 속성을 가져옵니다. 개인 속성을 포함합니다.
    Field[] fiels1 = clazz.getDeclaredFields();
    for(int i=0;i

    2. 속성의 각 부분의 내용을 얻는다
    권한 수식자 변수 형식 변수 이름
    1. 각 속성에 대한 권한 수식자 획득
    Field[] field = clazz.getDeclaredFields();
    	for(Field i:field) {
    	//1.            
    		int a = i.getModifiers();
    		String str1 = Modifier.toString(a);
    		System.out.print(str1+"   ");
    	}
    

    2. 속성의 변수 유형 가져오기
    Field[] field = clazz.getDeclaredFields();
    		for(Field i:field) {
    		//2.         
    		Class type = i.getType();
    		System.out.print(type+"  ");
    	}
    

    3. 속성명 얻기
    Class clazz = Person.class;
    		Field[] field = clazz.getDeclaredFields();
    		for(Field i:field) {
    		//3.     
    		System.out.print(i.getName());
    		System.out.println();
    	}
    	
    

    3. 런타임 클래스를 가져오는 방법(중점)
    1. getMethods () 실행 시 클래스와 부모 클래스의 모든 성명을public로 가져오는 방법
    Class clazz = Person.class;
    Method[] m1 = clazz.getMethods();
    	for(Method m:m1) {
    	System.out.println(m);
    	}
    

    2.getDeclaredMethods()는 런타임 클래스 자체가 선언한 모든 방법을 가져옵니다.
    Method[] methods = clazz.getDeclaredMethods();
    	for(int i=0;i

    4. 획득 방법의 각 부분에 대한 내용
    주석 권한 수식자 반환값 형식 방법 이름 참조 목록 이상
    주해
    Class clazz = Person.class;
    		
    	Method[] m1 = clazz.getMethods();
    	for(Method m:m1) {
    	Annotation[] an = m.getAnnotations();
    	for(Annotation a:an) {
    	    System.out.println(a);
    	}
    }
    

    2. 권한 수식자
    int a = m.getModifiers();
    String str1 = Modifier.toString(a);
    System.out.print(str1+"  ");
    
    

    3. 반환값 유형
    Class return1 = m.getReturnType();
    System.out.print(return1+"  ");
    
    

    4. 방법명
    System.out.print(m.getName()+"   ");
    
    

    5. 인삼 목록
    System.out.print("(");
    Class[] params = m.getParameterTypes();
    for(Class p : params) {
    	System.out.print(p.getName());
    }
    System.out.println(")"+"   ");
    
    

    6. 이상하게 던진다
    Class[] ex = m.getExceptionTypes();
    	for(Class e:ex) {
    		System.out.print(e.getName());
    	}
     //   for(int i=0;i

    5. 구조기 가져오기
    	@Test
    	public void test5() throws Exception {
    		
    		Class clazz = Class.forName("com.atguigu.java.Person");
    		
    		Constructor[] cons = clazz.getDeclaredConstructors();
    		for(Constructor c : cons) {
    			System.out.println(c);
    		}
    		
    	
    	}
    
    

    6. 런타임 클래스의 부모 클래스 가져오기
    @Test
    	public void test6() {
    		Class clazz = Person.class;
    		Class super1 = clazz.getSuperclass();
    		System.out.println(super1);
    	}
    
    

    7. 범용 부류 가져오기
    @Test
    	public void test7() {
    		Class clazz = Person.class;
    		Type type1 = clazz.getGenericSuperclass();
    		System.out.println(type1);
    	}
    
    

    8. 부류의 범주 가져오기(중점)
    @Test
    	public void test8() {
    		Class clazz = Person.class;
    		Type type1 = clazz.getGenericSuperclass();
    		
    		ParameterizedType param= (ParameterizedType)type1;
    		Type[] ars = param.getActualTypeArguments();
    		System.out.println((Class)ars[0]);
    	}
    
    

    9. 실현된 인터페이스 얻기
    @Test
    	public void test9() {
    		Class clazz = Person.class;
    		Class[] i = clazz.getInterfaces();
    		for(Class a:i) {
    			System.out.println(a);
    		}
    	}
    
    

    10. 가방 얻기
    @Test
    	public void test10() {
    		Class clazz = Person.class;
    		Package p = clazz.getPackage();
    		System.out.println(p);
    	}
    
    

    모든 코드는 다음과 같습니다.
    package com.atguigu.java;
    
    import java.lang.annotation.Annotation;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    import java.lang.reflect.Modifier;
    import java.lang.reflect.ParameterizedType;
    import java.lang.reflect.Type;
    
    import org.junit.Test;
    
    /**
     *             
     * 
     * @author MD
     *
     */
    public class TestField {
    
    	
    	/**
    	 * 1.         
    	 */
    	@Test
    	public void test1() {
    		Class clazz = Person.class;
    		
    		//1.getFields()    :        Field       
    		//                   public   
    //		Field[] fiels = clazz.getFields();
    //		for(int i=0;i

    정상으로 돌아오다
    5. 실행 시 클래스를 호출하는 지정 구조
    1. 실행 시 클래스가 지정한 속성을 호출하고 값을 부여합니다
    1. 지정된 속성 가져오기
    getField(String fieldName): 런타임 클래스에서 public로 명시된 속성의 fieldName 속성을 가져옵니다.
    Field name = clazz.getField("name");
    

    2. 런타임 클래스의 객체 만들기
    Person p = (Person) clazz.newInstance();
    System.out.println(p);
    
    

    3. 런타임 클래스에 지정된 속성 값을 지정합니다.
    name.set(p, "Jerry");
    System.out.println(p);
    
    

    age에 값을 부여하려면private에 주의해야 합니다
    getDeclareField(String fieldName): 런타임 클래스에서 filedName으로 표시된 속성을 가져옵니다.
    	Field age = clazz.getDeclaredField("age");
    	//            ,           ,               
    	age.setAccessible(true);//           
    	age.set(p,1);
    	System.out.println(p);
    
    

    id에 값을 부여합니다. 기본 수식자
    	Field id = clazz.getDeclaredField("id");
    	id.set(p,10);
    	System.out.println(p);
    
    

    2. 실행 시 클래스에서 지정한 방법을 호출합니다
    1.getMethod (String methodName, Class... params) 에서 지정한 공공 방법, 방법 이름, 매개 변수 목록을 가져옵니다.
    Class clazz = Person.class;
    Method m1 = clazz.getMethod("show");
    
    

    2. 런타임 클래스의 객체 만들기
    Person p =(Person)clazz.newInstance();
    
    

    3. 속성과 비슷합니다. invoke 키워드 안에 대상과 파라미터 목록이 있고 되돌아오는 값이 있을 수도 있습니다. Object로 받습니다.
    Object returnVal = m1.invoke(p);
    System.out.println(returnVal);//        null
    
    

    4. toString()에서 반환된 값을 가져옵니다.
    Method m2 = clazz.getMethod("toString");
    Object returnVal1 = m2.invoke(p);
    System.out.println(returnVal1);
    
    

    5. display () 인자가 있는
    Method m3 = clazz.getMethod("display",String.class);
    m3.invoke(p, "china");
    
    

    6. info() 정적 가져오기 방법
    Method m4 = clazz.getMethod("info");
    m4.invoke(Person.class);
    
    

    7. Test () 의 개인 매개 변수와 되돌아오는 값을 가져옵니다
    Method m5 = clazz.getDeclaredMethod("Test",String.class,Integer.class);
    m5.setAccessible(true);
    Object o = m5.invoke(p,"  ",5);
    System.out.println(o);
    
    

    3. 지정한 구조기를 호출하여 클래스 대상을 만든다
    public void test3() throws InstantiationException, Exception {
    		Class clazz = Person.class;
    		Constructor cons = clazz.getDeclaredConstructor(String.class,int.class);
    		cons.setAccessible(true);
    		Person p = (Person)cons.newInstance("    ",20);
    		System.out.println(p);
    
    		
    	}
    
    

    모든 코드
    package com.atguigu.java;
    
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    
    import org.junit.Test;
    
    /**
     * ******               (  、  )
     * @author MD
     *
     */
    public class TestField1 {
    	/**
    	 *            
    	 * @throws Exception 
    	 * @throws NoSuchFieldException 
    	 */
    	
    	@Test
    	public void test1() throws Exception {
    		Class clazz = Person.class;
    		
    		//1.       
    		//getField(String fieldName):          public        fieldName   
    		Field name = clazz.getField("name");
    		//2.         
    		Person p = (Person) clazz.newInstance();
    		System.out.println(p);
    		//3.            
    		name.set(p, "Jerry");
    		System.out.println(p);
    		
    		// age  ,private    
    		//getDeclareField(String fieldName):          filedName   
    		Field age = clazz.getDeclaredField("age");
    		//            ,           ,               
    		age.setAccessible(true);//           
    		age.set(p,1);
    		System.out.println(p);
    				
    		// id  ,      
    		Field id = clazz.getDeclaredField("id");
    		id.set(p,10);
    		System.out.println(p);
    		
    	}
    		
    	/**
    	 *             
    	 * @throws Exception 
    	 * @throws NoSuchMethodException 
    	 */
    	@Test
    	public void test2() throws NoSuchMethodException, Exception {
    		Class clazz = Person.class;
    		
    		//getMethod(String methodName,Class...params)     public  ,   ,    
    		Method m1 = clazz.getMethod("show");
    		
    		//         
    		Person p =(Person)clazz.newInstance();
    		
    		//     ,   invoke             ,       , Object  
    		Object returnVal = m1.invoke(p);
    		System.out.println(returnVal);
    				
    		//  toString()     
    		Method m2 = clazz.getMethod("toString");
    		Object returnVal1 = m2.invoke(p);
    		System.out.println(returnVal1);
    		
    		//  display()    
    		Method m3 = clazz.getMethod("display",String.class);
    		m3.invoke(p, "china");
    				
    		//  info()     
    		Method m4 = clazz.getMethod("info");
    		m4.invoke(Person.class);
    				
    		//  Test()             
    		Method m5 = clazz.getDeclaredMethod("Test",String.class,Integer.class);
    		m5.setAccessible(true);
    		Object o = m5.invoke(p,"  ",5);
    		System.out.println(o);	
    	}
    	
    	
    	/**
    	 *         ,     
    	 * @throws Exception 
    	 * @throws InstantiationException 
    	 */
    	
    	@Test
    	public void test3() throws InstantiationException, Exception {
    		Class clazz = Person.class;	
    		Constructor cons = clazz.getDeclaredConstructor(String.class,int.class);
    		cons.setAccessible(true);
    		Person p = (Person)cons.newInstance("    ",20);
    		System.out.println(p);
    	}
    }
    

    정상으로 돌아오다
    6. ClassLoader
    클래스 마운트는 클래스 (class) 를 메모리에 불러오는 데 사용됩니다.
    1. 시스템 클래스 마운트 가져오기
    ClassLoader loader1 = ClassLoader.getSystemClassLoader();
    System.out.println(loader1);
    

    2. 시스템 클래스 마운트의 부모 클래스 마운트, 즉 확장 클래스 마운트 가져오기
    ClassLoader loader2 = loader1.getParent();
    System.out.println(loader2);
    

    3. 확장 클래스 마운트의 부모 클래스 마운트기, 즉 유도 클래스 마운트기를 가져옵니다. 마운트된 것은 핵심 라이브러리입니다.null로 인쇄됩니다.
    ClassLoader loader3 = loader2.getParent();
    System.out.println(loader3);
    

    4. 현재 클래스가 어떤 클래스 마운트에 의해 마운트되는지 테스트
    Class clazz1 = Person.class;
    ClassLoader loader4 = clazz1.getClassLoader();
    System.out.println(loader4);//      
    

    1. JVM이 class 파일을 로드하는 원리에 대해 설명합니까?
    JVM의 클래스 마운트는 ClassLoader와 해당 하위 클래스로 이루어집니다.
    Java ClassLoader는 중요한 Java 런타임 시스템 구성 요소입니다.이것은 실행할 때 클래스 파일의 클래스를 찾고 불러오는 것을 책임집니다.

    좋은 웹페이지 즐겨찾기