๐Ÿ’ป

Java ํ”„๋กœ๊ทธ๋ž˜๋ฐ - [๊ธฐ๋ณธ API ํด๋ž˜์Šค] Class ํด๋ž˜์Šค(getClass(), forName(), getDeclaredConstructors(), newInstance()) ๋ณธ๋ฌธ

KITRI/JAVA

Java ํ”„๋กœ๊ทธ๋ž˜๋ฐ - [๊ธฐ๋ณธ API ํด๋ž˜์Šค] Class ํด๋ž˜์Šค(getClass(), forName(), getDeclaredConstructors(), newInstance())

๋˜ํšจ๋‹ˆ 2020. 5. 12. 14:40
  • Class ๊ฐ์ฒด ์–ป๊ธฐ getClass(), forName() : ํ”„๋กœ๊ทธ๋žจ์—ฅ์„œ Class๊ฐ์ฒด๋ฅผ ์–ป๊ธฐ ์œ„ํ•ด์„œ๋Š” Objectํด๋ž˜์Šค๊ฐ€ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” getClass() ๋ฉ”์†Œ๋“œ๋ฅผ ์ด์šฉํ•˜๋ฉด๋œ๋‹ค.  Object๋Š” ๋ชจ๋“  ํด๋ž˜์Šค์˜ ์ตœ์ƒ์œ„ ํด๋ž˜์Šค์ด๋ฏ€๋กœ ๋ชจ๋“  ํด๋ž˜์Šค์—์„œ getClass() ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•  ์ˆ˜ ์žˆ๋‹ค. 

 

  • ๋ฆฌํ”Œ๋ ‰์…˜ getDeclaredConstructors(), getDeclaredFields(), getDeclaredMethods() : ํด๋ž˜์Šค ์ƒ์„ฑ์ž, ํ•„๋“œ์ •๋ณด, ๋ฉ”์†Œ๋“œ ์ •๋ณด๋ฅผ ์•Œ๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค. Constructor, Field, Method ํด๋ž˜์Šค๋Š” ๋ชจ๋‘ java.lang.reflect ํŒจํ‚ค์ง€์— ์†Œ์†๋˜์–ด ์žˆ๋‹ค. 

 

  • ๋™์  ๊ฐ์ฒด ์ƒ์„ฑ newInstance() :  ๋™์ ๊ฐ์ฒด ์ƒ์„ฑ์‹œ ์‚ฌ์šฉํ•œ๋‹ค. ๊ธฐ๋ณธ ์ƒ์„ฑ์ž๋ฅผ ํ˜ธ์ถœํ•ด์„œ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ฐ˜๋“œ์‹œ ํด๋ž˜์Šค์— ๊ธฐ๋ณธ ์ƒ์„ฑ์ž๊ฐ€ ์กด์žฌํ•ด์•ผ ํ•œ๋‹ค. ๋งŒ์•ฝ ๋งค๊ฐœ ๋ณ€์ˆ˜๊ฐ€ ์žˆ๋Š” ์ƒ์„ฑ์ž๋ฅผ ํ˜ธ์ถœํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ๋ฆฌํ”Œ๋ ‰์…˜์œผ๋กœ Constructor ๊ฐ์ฒด๋ฅผ ์–ป์–ด newInstance() ๋ฉ”์†Œ๋“œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด ๋œ๋‹ค.  

 

 

[์ฐธ๊ณ ]

https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Class.html#newInstance()

 

Class (Java SE 14 & JDK 14)

Type Parameters: T - the type of the class modeled by this Class object. For example, the type of String.class is Class . Use Class if the class being modeled is unknown. All Implemented Interfaces: Serializable, Constable, TypeDescriptor, TypeDescriptor.O

docs.oracle.com

 

 

 

์—ฌ๊ธฐ์„œ๋Š” ๋ฐฐ์—ด๋กœ ๋ฐ›์•„์คฌ์ง€๋งŒ ํ›„์— map์œผ๋กœ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ๋ฐฐ์šธ ๊ฒƒ์ด๋‹ค. 

 

๋ฐ˜์‘ํ˜•
Comments