Java Reflection Tutorial: Java POJO 만들기 Reflection API를 사용하여 ClassName, DeclaredFields, ObjectType, SuperType 등을 가져옵니다.
게시 됨: 2019-06-10
Reflection API를 사용하여 Java에서 모든 선언된 클래스 필드를 가져오는 가장 좋은 프로그래밍 방식
이 튜토리얼에서는 먼저 간단한 Java POJO를 작성하고 POJO에서 모든 Java Reflection 예제를 수행할 것입니다. 용어 POJO에 대해 들어봤을 것입니다. Plain Old Java Object 란 무엇입니까?
또한 아래 질문이 있는 경우 올바른 위치에 있습니다.
- 자바 – POJO를 만드는 방법?
- java – 간단한 POJO 클래스 생성
- Java의 POJO(Plain Old Java Objects)
- POJO(Plain Old Java Object) 소개
- POJO 클래스 디자인하기
- 첫 번째 Java POJO 클래스 생성
POJO 는 제한 사항이 제거된 단순하고 오래된 Java Bean 입니다. Java Beans는 다음 요구 사항을 충족해야 합니다.
- foo라는 이름의 변경 가능한 속성에 대해
getFoo(또는 부울의 경우isFoo) 및setFoo메소드의 Bean 규칙을 따르십시오. foo가 변경 불가능한 경우 setFoo를 생략합니다. -
no-arg기본 생성자 -
java.io.Serializable을 구현해야 합니다.
POJO는 이들 중 어느 것도 요구하지 않습니다. 이름에서 알 수 있듯이 JDK에서 컴파일되는 객체는 Plain Old Java Object로 간주될 수 있습니다.
앱 서버, 기본 클래스, 인터페이스가 필요하지 않습니다.
CrunchifyPOJO.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
package crunchify . com . tutorials ; /** * @author Crunchify.com Simple POJO Example */ public class CrunchifyPOJO { public String name ; protected String webAddress ; public String email ; protected int zip ; public CrunchifyPOJO ( ) { name = "Crunchify.com" ; webAddress = "https://crunchify.com" ; } // ========================================================== // Create a Setters and Getters for all variables // ========================================================== public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } protected String getWebAddress ( ) { return webAddress ; } protected void setWebAddress ( String webAddress ) { this . webAddress = webAddress ; } public String getEmail ( ) { return email ; } public void setEmail ( String email ) { this . email = email ; } protected int getZip ( ) { return zip ; } protected void setZip ( int zip ) { this . zip = zip ; } public void thisIsCrunchifyReflection ( ) { System . out . println ( "- Hey This is Crunchify's Refection API tutorials. More than 400 Tutorials on Crunchify.com" ) ; } // ========================================================== // Create a String description of a Crunchify credentials // ========================================================== public String toString ( ) { String result = "Name: " + getName ( ) + "\n" ; result += "WebAddress: " + getWebAddress ( ) + "\n" ; result += "email: " + getEmail ( ) + "\n" ; result += "zip: " + getZip ( ) + "\n" ; return result ; } public static void main ( String [ ] args ) { // Create and print a CrunchifyPOJO object ... CrunchifyPOJO crunchify = new CrunchifyPOJO ( ) ; crunchify . setName ( "Crunchify.com" ) ; crunchify . setWebAddress ( "https://crunchify.com" ) ; crunchify . setZip ( 95124 ) ; System . out . println ( crunchify ) ; } } |
결과:
|
1 2 3 4 |
Name : Crunchify . com WebAddress : https : //crunchify.com email : test @ crunchify . com zip : 95124 |

이제 이 POJO를 기반으로 한 Java Reflection's Example 를 살펴보겠습니다.
아래 예제 클래스 CrunchifyReflectionTutorial.java 를 살펴보십시오. 여기에는 총 9개의 다른 Java Reflection API 예제가 포함됩니다.
자바 프로그램을 실행하고 있습니까?
컴파일 타임에 클래스, 메서드 등의 이름을 모른 채 런타임에 클래스, 인터페이스, 필드 및 메서드를 검사하려면 어떻게 해야 할까요? 음, Reflection의 도움으로 매우 쉽게 가능합니다.
리플렉션은 일반적으로 Java 가상 머신에서 실행되는 애플리케이션의 런타임 동작을 검사하거나 수정하는 기능이 필요한 프로그램에서 사용됩니다.
Java Reflection에 관하여 아래 질문이 있는 경우 올바른 위치에 있는 것입니다.
- 클래스, 메소드, 필드에 대한 Java 리플렉션 튜토리얼
- Java Reflection API를 사용한 동적 클래스 로딩
- Java Reflection API 자세히 살펴보기
- 자바 API 리플렉션 – 생성자 객체를 사용하여 객체를 생성하는 방법
- 리플렉션 – Java 메서드를 호출하는 방법
- Reflection을 사용하여 런타임에 Java 메서드를 호출하는 방법
- 인수가 없는 Java 반사 호출 메소드
- 클래스 이름, CanonicalName 및 SimpleName을 얻는 방법
- 클래스 객체가 Array 클래스를 나타내는지 알아봅시다.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
package crunchify . com . tutorials ; import java . lang . reflect . Constructor ; import java . lang . reflect . Field ; import java . lang . reflect . Method ; /** * @author Crunchify.com * */ public class CrunchifyReflectionTutorial { public static void main ( String [ ] args ) { CrunchifyPOJO crunchify = new CrunchifyPOJO ( ) ; System . out . println ( "Crunchify Object: ====================\n" + crunchify ) ; // How to find out the Object belongs to which class? Class <? > clazz = crunchify . getClass ( ) ; // Example 1: ==================== How to get the Class's Name, // CanonicalName and SimpleName? String clazzName = clazz . getName ( ) ; String clazzCanonicalName = clazz . getCanonicalName ( ) ; String clazzSimpleName = clazz . getSimpleName ( ) ; System . out . println ( "How to get the Class's Name, CanonicalName and SimpleName? ==================== Example 1" ) ; System . out . println ( "1. clazzName: " + clazzName + ", \n2. clazzCanonicalName: " + clazzCanonicalName + ", \n3. clazzSimpleName: " + clazzSimpleName + "\n" ) ; // Example 2: ==================== Let's find out if class object // represents an Array class int [ ] [ ] crunchifyArr = { { 1 , 1 } , { 2 , 1 } } ; Class <? extends int [ ] [ ] > arrClazz = crunchifyArr . getClass ( ) ; System . out . println ( "Let's find out if class object represents an Array class ==================== Example 2" ) ; if ( arrClazz . isArray ( ) ) { System . out . println ( "- " + arrClazz . getSimpleName ( ) + " is an array class.\n" ) ; } else { System . out . println ( "- " + clazz . getSimpleName ( ) + " is not an array class.\n" ) ; } // Example 3: ==================== Let's find out Object's Type Double crunchifyDouble = 11.1 ; System . out . println ( "Let's find out Object's Type ==================== Example 3" ) ; System . out . println ( "- 11.1 is of Type: " + crunchifyDouble . getClass ( ) . getName ( ) + "\n" ) ; // Example 4: ==================== How to get SuperClass System . out . println ( "How to get SuperClass ==================== Example 4" ) ; System . out . println ( "1. Superclass of crunchify: " + crunchify . getClass ( ) . getSuperclass ( ) + "\n2. Superclass of crunchifyDouble: " + crunchifyDouble . getClass ( ) . getSuperclass ( ) + "\n" ) ; // Example 5: ==================== How to check if class is Primitive // Type of not? System . out . println ( "How to check if class is Primitive Type of not? ==================== Example 5" ) ; System . out . println ( "1. Is 'int' a Prmitive Type: " + int . class . isPrimitive ( ) ) ; System . out . println ( "2. Is 'String' a Prmitive Type: " + String . class . isPrimitive ( ) ) ; System . out . println ( "3. Is 'double' a Prmitive Type: " + double . class . isPrimitive ( ) ) ; // Example 6: ==================== How to create an object using // Constructor object? // A constructor reflection to create a string object by calling // String(String) and String(StringBuilder) constructors. Class < String > clazzString = String . class ; System . out . println ( "\nHow to create object using Constructor object? ==================== Example 6" ) ; try { Constructor <? > constructor = clazzString . getConstructor ( new Class [ ] { String . class } ) ; String object = ( String ) constructor . newInstance ( new Object [ ] { "Hello World!" } ) ; System . out . println ( "1. String.class = " + object ) ; constructor = clazzString . getConstructor ( new Class [ ] { StringBuilder . class } ) ; object = ( String ) constructor . newInstance ( new Object [ ] { new StringBuilder ( "Hello Universe!" ) } ) ; System . out . println ( "2. StringBuilder.class = " + object ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } // Example 7: ==================== How to get constructors of a class // object? System . out . println ( "\nHow to get constructors of a class object ==================== Example 7" ) ; try { Constructor <? extends CrunchifyPOJO > constructor = crunchify . getClass ( ) . getConstructor ( ) ; System . out . println ( "- Constructor = " + constructor . getName ( ) ) ; } catch ( NoSuchMethodException e ) { e . printStackTrace ( ) ; } // Example 8: ==================== How to get field of a class object try { System . out . println ( "\nHow to get field of a class object ==================== Example 8" ) ; Field [ ] methods = clazz . getFields ( ) ; for ( Field temp : methods ) { System . out . println ( "- " + temp . getName ( ) ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } // Example 9: ==================== How to invoke a method using Method // class? try { System . out . println ( "\nHow to invoke a method using Method class ==================== Example 9" ) ; Class <? > c = Class . forName ( "crunchify.com.tutorials.CrunchifyPOJO" ) ; Object obj = c . newInstance ( ) ; Method method = c . getDeclaredMethod ( "thisIsCrunchifyReflection" ) ; method . invoke ( obj ) ; } catch ( Exception e ) { System . out . println ( e ) ; } // Example 10: ==================== get all Declared Class Fields Field [ ] crunchifyFields = CrunchifyPOJO . class . getDeclaredFields ( ) ; System . out . println ( "\nget all Declared Class Fields ==================== Example 10" ) ; for ( Field field : crunchifyFields ) { Class < ? > type = field . getType ( ) ; System . out . println ( "field name : " + field . getName ( ) + " , type : " + type ) ; } } } |
결과:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
Crunchify Object : ==================== Name : Crunchify . com WebAddress : https : //crunchify.com email : test @ crunchify . com zip : 0 How to get the Class 's Name, CanonicalName and SimpleName? ==================== Example 1 1. clazzName: crunchify.com.tutorials.CrunchifyPOJO, 2. clazzCanonicalName: crunchify.com.tutorials.CrunchifyPOJO, 3. clazzSimpleName: CrunchifyPOJO Let' s find out if class object represents an Array class ==================== Example 2 - int [ ] [ ] is an array class . Let 's find out Object' s Type ==================== Example 3 - 11.1 is of Type : java . lang . Double How to get SuperClass ==================== Example 4 1. Superclass of crunchify : class java . lang . Object 2. Superclass of crunchifyDouble : class java . lang . Number How to check if class is Primitive Type of not ? ==================== Example 5 1. Is 'int' a Prmitive Type : true 2. Is 'String' a Prmitive Type : false 3. Is 'double' a Prmitive Type : true How to create object using Constructor object ? ==================== Example 6 1. String . class = Hello World ! 2. StringBuilder . class = Hello Universe ! How to get constructors of a class object ==================== Example 7 - Constructor = crunchify . com . tutorials . CrunchifyPOJO How to get field of a class object ==================== Example 8 - name - email How to invoke a method using Method class ==================== Example 9 - Hey This is Crunchify ' s Refection API tutorials . More than 400 Tutorials on Crunchify . com get all Declared Class Fields ==================== Example 10 field name : name , type : class java . lang . String field name : webAddress , type : class java . lang . String field name : email , type : class java . lang . String field name : zip , type : int |
프로그램 자체에 최대한 많은 시스템을 넣으려고 최선을 다했기 때문에 완전한 예제는 스스로 설명할 수 있습니다.

그것을 시도하고 질문이 있으면 저에게 알려주십시오. 즐거운 코딩.
