JAVA API - 반사, 주해, JVM

17502 단어 JAVAAPI
package ReflectDemo;

import java.awt.List;

/*
 *     
 *   1.  
        	   
       		  :                 。
       		  :          
       		
       		Service       
       				1.Dao d=new MySQLDao(); d.add()    ->Dao d=new OracleDao() d.add();
       				2.  sql.properties  ,                 ,                 ?-------  
       		Dao        ,              。
       				1.MysqlDao ,OracleDao
       			
       	          :2.sql.properties  dao=MySQLDao();
       	     
      2.  :                    。
           
      
         Class,  	       ,     
      //Package,	          
         Field,  	      
         Method, 	      
         Constructor        
       //Annotation       
         
         
      3.  Class  
        3.1    .class             
        3.2    .getClass()               
        3.3  Class.forName(      );         
 */
public class ReflectDemo01 {
	public static void main(String[] args) throws ClassNotFoundException {
		
		//Class        ,     Class           
		
//-------------------3.1    .class             -----------------------		
		
		//A     1.   2    3.  
		
		//1.clz  String     
		Class clz=String.class;   
		System.out.println(clz);            //  class java.lang.String
		
		
		//2.clz2  list      
		Class  clz2=List.class;
		System.out.println(clz2);          //  class java.awt.List
		
		//3.clz3  int[]       
		Class clz3= int[].class;
		System.out.println(clz3);         //  class [I
		  
		
		//B    
		//double    
		Class clz4=Double.class;   
		System.out.println(clz4);         //  class java.lang.Double
		
//------------------3.2    .getClass()                ---------------------------------		
		//clz5  String     
		Object o="abc";
		Class  clz5=(Class)o.getClass();
		System.out.println(clz5);         //  class java.lang.String
		
//--------------------3.3  Class.forName(      );          -------------------------------------
		Class clz6=(Class) Class.forName("java.lang.String");
		System.out.println(clz6);         //  class java.lang.String
	}
}
package ReflectDemo;

import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectDemo02 {
	public static void main(String[] args) throws  Exception{
	
//             (               )
		
//------------------      .newInstance()-------------------	
		//1.    Object         
		Class clz=(Class) Class.forName("java.lang.Object");
		//  Object     .newInstance()
		Object o=clz.newInstance();
		System.out.println(o);           //  java.lang.Object@55f96302
		
		
		//2.  String  
		Class clz2=(Class) Class.forName("java.lang.String");
		//                .newInstance()
		String str=clz2.newInstance();
		System.out.println(str);         //   
		 
		
//------------------4.        Constructor        -------------------------------	
//1.  public    
//.getConstructor(   )  public    
//.newInstance(  )          
		

//2.        
//.getDeclaredConstructor(   )
//.setAccessible(true);     
//.newInstance(  )          
	
//3.        
//.getDeclaredConstructors()
		
		
		//3.       Integer  
		Class clz3=Integer.class;
		//Integer in=clz3.newInstance();        .newInstance()    
		
		//         ,     Integer(int)
		Constructor c=clz3.getConstructor(int.class);
		//      ,        
		Integer in=c.newInstance(5);
		
		/*
		 * Constructor c=clz3.getConstructor(int.class);
		   Integer in=c.newInstance(5);
		      
		   Integer in=new Integer(5);
		 */
		
		System.out.println(in);         //  5
		
		
		//4.1       String  
		Class clz4=String.class;
		Constructor c2=clz4.getConstructor(String.class);
		//      ,        
		String str2=c2.newInstance("abc");
		System.out.println(str2);     //  abc
		
		
		//4.2.getConstructor()    public     
		//Constructor c3=clz4.getConstructor(char[].class,boolean.class);      
		//System.out.println(c3);
		
		//4.3.getDeclaredConstructor()             ,        
		Constructor c4=clz4.getDeclaredConstructor(char[].class, boolean.class);
		//.setAccessible(true)    /  ,       
		c4.setAccessible(true);
		System.out.println(c4.newInstance(new char[] {'a','d','s'} ,true));   //  ads

		
		
		//5.         
		Class clz5=String.class;
		Constructor[]  cs=clz5.getDeclaredConstructors();
		for(Constructor cst:cs) {
			System.out.println(cst);
		}
		//  
		/*
		 * public java.lang.String(byte[],int,int)
			public java.lang.String(byte[],java.nio.charset.Charset)
			public java.lang.String(byte[],java.lang.String) throws java.io.UnsupportedEncodingException
			public java.lang.String(byte[],int,int,java.nio.charset.Charset)
			public java.lang.String(byte[],int,int,java.lang.String) throws java.io.UnsupportedEncodingException
			java.lang.String(char[],boolean)
			public java.lang.String(java.lang.StringBuilder)
			public java.lang.String(java.lang.StringBuffer)
			public java.lang.String(byte[])
			public java.lang.String(int[],int,int)
			public java.lang.String()
			public java.lang.String(char[])
			public java.lang.String(java.lang.String)
			public java.lang.String(char[],int,int)
			public java.lang.String(byte[],int)
			public java.lang.String(byte[],int,int,int)
		 */
		
//----------------------5.      Method      --------------	
//----------Method .getDeclaredMethod()----------
//----------[setAccessible(true)      ]---
//----------invoke()  ----------
		
		//6.1          public  charAt(int)
		Method m=clz5.getDeclaredMethod("charAt", int.class);
		String str4="sadadsa";
		//    
		 char c5=(char) m.invoke(str4, 5);
		 System.out.println(c5);    //  s
		 
		 //        
		 Method m1=clz5.getDeclaredMethod("length");
		 int  len=(int) m1.invoke(str4);
		 System.out.println(len);    //  7
		 
		 //6.2               
		Method m2=clz5.getDeclaredMethod("indexOfSupplementary",int.class,int.class);     
	    //    /  ,       
		 m2.setAccessible(true);
		 int i=(int) m2.invoke(str4, 1,5);
		 System.out.println(i);    //  -1


//------------------6.       Field-      --------------------
//-------------Field .getDeclaredField(  )--------------------------------
//-------------[setAccessible(true)      ]-------------------------
//--------------set    ,get    --------------------------------
		 Class clz6=String.class;
		 Field f=clz6.getDeclaredField("hash");
		 System.out.println(f);            //  private int java.lang.String.hash
		 f.setAccessible(true);
		 f.set(str, 248);               //    
		 System.out.println(f.get(str));//       //  248
		 

//----------------7. getEnumConstants()      ------------------------------------
		 //            
		 Class clz7=Level.class;
		 Level[] is=clz7.getEnumConstants(); //         ,  null
		 for(Level lv:is) {
			 System.out.println(lv);   //  ABCD
		 }
		//          ,   null
		System.out.println(clz.getEnumConstants());//  null
		 
		
//--------------8.        Package .getPackage()---------------------
		Package p = clz7.getPackage(); 
		System.out.println(p);         //  package ReflectDemo
		
		
		
//---------------9.           getName()------------------------------
		 System.out.println(clz7.getName()); //  ReflectDemo.Level
		
		 
		 
//--------------10.         .getSimpleName()-----------------------------
		System.out.println(clz7.getSimpleName());//  Level

			//          ,   null
			// System.out.println(clz.getEnumConstants());
		 
		 
		 
	
// --------------11.            .getInterfaces()-------------------------
		// Class clz6=String.class;
		 Class[] cs2=clz6.getInterfaces();
		 for(Class sd:cs2) {
			 System.out.println(sd);  //  interface java.io.Serializable interface java.lang.Comparable interface java.lang.CharSequence
		 }

//--------------12.                .getSuperclass()-------------------------
		 System.out.println(clz6.getSuperclass()); //  class java.lang.Object
		 

		
	
//-----------13.             isAnonymousClass()-----------------------
		 A a=new A() {
			 
		 };
		 System.out.println(a.getClass().isAnonymousClass());  //  true

//-----------14.            isLocalClass()------------------------------
		 class B{ }
		 System.out.println(B.class.isLocalClass());    //  true
		 
//-----------15.            .isMemberClass()----------------------------
		 System.out.println(B.class.isMemberClass());    //  false
		System.out.println(String.class.isMemberClass()); //  false
		 

//------------16.              .isPrimitive()--------------------
		Class clz10 = Object.class;
		
		System.out.println(clz.isPrimitive());        //  false
		System.out.println(short.class.isPrimitive());//  true
		
		
//------------17.               .isAssignableFrom()------------------
		System.out.println(Serializable.class.isAssignableFrom(String.class)); //  true
		 
		Class clz9=Object.class;
		 System.out.println(clz9.isAssignableFrom(Object.class));   //  true
		
	
//----------- 18.            .isArray()-----------------------------
		 Class clz8=String[].class;
		 System.out.println(clz8.isArray());              //  true
		 
		 
//------------19.            .isInterface()---------------------------
		 System.out.println(clz8.isInterface());    //  false
		 
		 
//------------20.               .isInstance()---------------------
		 Object z="abc";
		 System.out.println(clz8.isInstance(z));    //  false
		 
		
		
		 
		
	}
}

enum Level{
	A,B,C,D;
}

class A{
	
}
package ReflectDemo;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectDemo03 {
	public static void main(String[] args) throws Exception {
		Class clz=String.class;
		
//------------1.          .getType()-----------------
		Field f=clz.getDeclaredField("hash");
		System.out.println(f.getType());       //  int
		
		
//-----------2.           .isEnumConstant()------------------
		System.out.println(f.isEnumConstant());//  false
		
		
//----------3.           .getExceptionTypes()--------------
		Method m=clz.getDeclaredMethod("getBytes", String.class);
		
		Class[] es=m.getExceptionTypes();
		for(Class e:es) {
			System.out.println(e);  //  class java.io.UnsupportedEncodingException
		}
		
		
//-------------4.      .getName()---------------------------------------
		System.out.println(m.getName());  //  getBytes
		
//-----------5.          .getParameterTypes()---------------------
		Class[] ps=m.getParameterTypes();
		for(Class e:ps) {
			System.out.println(e);      //  class java.lang.String
		}
		
//------------6.         .getReturnType()-----------------------
		System.out.println(m.getReturnType()); //  class [B
		
//-------------7.          .isVarArgs()----------------------
		System.out.println(m.isVarArgs());  //  false
		
		
		//           ------------------
	}
}
package Note;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/*
 *   :
 *          , JAVA       Annotation
 *  1.
 *    1.1 @interface      
 *    1.2              ,               public static final
 *    1.3        ()              ,  ,String,Class,      ,           
 *    1.4default     
 *    1.5.             ,        ,          ,                           { , } 	
 *    1.6                Value,                    
 * 
 *  2.   :       
 *    2.1@Target         
 *    2.2@Retention             --------   --------------234--
 *    2.3@Documented                   
 *    2.4@Inherited                 
 *    
 *  
 */


//1.5             ,        ,          ,                           { , } 							           
@Time(year=2018,month=07,time= {2,5})

//1.6                Value,                    
@SAnno("ded")

public class NoteDemo {
	@SAnno("ded")
	public void m1(@SAnno("ded") int i) {};
}

//1.1 @interface      
@interface Time{
	//1.2              ,               
	//public static final int year=18
	//int year=18 ;
	
	
	//1.3        ()
	//             ,  ,String,Class,      ,           
	int year();
	int[] month();
	double[] time();
	int day()default 28;   //1.4.default     
	
	
	//boolean flag();    
	//Object  o();  1.3  ,             ,  ,String,Class,      ,           
	//String str();
}

//2.1@Target          
//    ,  ,  ,     
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD, ElementType.PARAMETER})


//2.3@Documented                   
@Documented  
@interface SAnno{
	String value();//1.6                Value,                    
}

package JVM;
/*
 * JVM  
 * 
     :-d,-ea
      : -X
     :-XX
 
 1.   
                ,               
 JVM             2G       1/3(       )
 *      4G   1/3=1.3G          16G  2G
 * 
 *-Xss128K            128K ,  Run as -> Run configurations->Arguments->VM arguments->   -Xss128K
 *
 *2.   
 *-Xmn           
 *-Xms             
 *-Xmx            
 *-XX:+PrintGCDetails   GC    
 *-Xmn5M -Xms10M -Xmx10M -XX:+PrintGCDetails 
 *
 *  :               ,        ,        。
 *
 *
 *
 *
 *
 *3.       
 *Copying   
 *Mark-sweeping        //  ,         
 *Mark-cleaning     
 *
 */
public class JVMDemo01 {
   static int count=0;
	public static void main(String[] args) {
		
		//     ,  Run as -> Run configurations->Arguments->VM arguments->   -Xss128K       
		//add(10000);       
		//   893,   893 java.lang.StackOverflowError   
		
		//  Run as -> Run configurations->Arguments->VM arguments->   -Xmn5M -Xms10M -Xmx10M -XX:+PrintGCDetails   
		byte[] bs=new byte[1024*1024*8];  //8M=8*1024k=8*1024*1024b  
		//  java.lang.OutOfMemoryError: Java heap space      
		
		
	}
	
	//    
    public static int add(int n) {
    	System.out.println(count++);
    	if(n==1)return 1;
    	return n+add(--n);
    }
}

 
다음은 반사 간단 한 예 다.
1. Dao 인터페이스
package ReflectDemoExer;

/*
 * Dao        ,              。
       			1.MysqlDao ,OracleDao
 */
//DAO          
public interface Dao {

	void add(String name);

	void delete(String name);

}

2.MySqlDao
package ReflectDemoExer;


//Mysql      Dao  
public class MySQLDao implements Dao {

	@Override
	public void add(String name) {
		System.out.println(" MySQL         :" + name);
	}

	@Override
	public void delete(String name) {
		System.out.println(" MySQL         :" + name);
	}

}

3.OracleDAO
package ReflectDemoExer;


//OracleDao      Dao  
public class OracleDao implements Dao {

	@Override
	public void add(String name) {
		System.out.println(" Oracle         :" + name);
	}

	@Override
	public void delete(String name) {
		System.out.println(" Oracle         :" + name);
	}

}

4.dao.properties
dao=ReflectDemoExer.MySQLDao

5.DaoFactory
package ReflectDemoExer;

import java.io.FileInputStream;
import java.util.Properties;


//  Dao  ,   Service  
public class DaoFactory {
	//    
	private static DaoFactory factory = new DaoFactory();
	private Properties prop;

	//     
	private DaoFactory() {
	}

	//    Dao  
	public static DaoFactory getFactory() {
		return factory;
	}

	//      Dao  
	@SuppressWarnings("unchecked")
	public Dao getInstance() {
        //  properties    
		prop = new Properties();
		try {
			prop.load(new FileInputStream("dao.properties"));

			String dao = prop.getProperty("dao");

			/*
			 *       Class.forName(      );         
					Class clz6=(Class) Class.forName("java.lang.String");
					System.out.println(clz6);         //  class java.lang.String
			 */
			
			Class clz = (Class) Class.forName(dao);//        ->  

			
			/*
			 * 
			 *       .newInstance()
			 * 1.    Object         
					Class clz=(Class) Class.forName("java.lang.Object");
			  2.  Object     .newInstance()
					Object o=clz.newInstance();
					System.out.println(o);           //  java.lang.Object@55f96302
			 */
			return clz.newInstance();   //     Dao  
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;   //    null
	}

}

6.Service.java
package ReflectDemoExer;

import org.junit.Test;

/*
 * Service       
       			1.Dao d=new MySQLDao(); d.add()    ->Dao d=new OracleDao() d.add();
       			2.  sql.properties  ,                 ,                 ?-------  
 */

public class Service {

	Dao d = DaoFactory.getFactory().getInstance();
	//Dao d= new MysqlDao();  d.add(name)
	//Dao d=new OracleDao();  d.add(name)

	public void add(String name) {
		
		//     

		//                   
		d.add(name);
	}

	public void delete(String name) {

		d.delete(name);
	}
	
	
	//  ,dao.properties     dao=ReflectDemoExer.OracleDao   Oracle         :Tom
	//dao.properties     dao=ReflectDemoExer.MySQLDao   Mysql         :Tom   
	@Test
	public void test(){
		
		delete("Tom");
		
	}

}

좋은 웹페이지 즐겨찾기