๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Java·๏ปฟServlet·๏ปฟJSP

[JAVA] Class ํด๋ž˜์Šค๋ฅผ ์ด์šฉํ•ด ๋ฉ”์†Œ๋“œ์™€ ์ƒ์„ฑ์ž ์–ป๊ธฐ

by Leica 2023. 2. 12.
๋ฐ˜์‘ํ˜•

JAVA์˜ Class ํด๋ž˜์Šค

Object์˜ getClass() ๋ฉ”์†Œ๋“œ๋Š” Class ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. Class ํด๋ž˜์Šค๋Š” ํ•ด๋‹น ํด๋ž˜์Šค์— ์„ ์–ธ๋œ ๋ฉ”์†Œ๋“œ์™€ ์ƒ์„ฑ์ž๋“ค์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฉ”์†Œ๋“œ๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค. getDeclaredConstructors(), getMethods()๊ฐ€ ๊ทธ๋Ÿฌํ•œ ๋ฉ”์†Œ๋“œ๋“ค์ž…๋‹ˆ๋‹ค.

 

Class#getName()

Object obj = new Object();
Class clazz = obj.getClass();
System.out.println(clazz.getName());

๐Ÿ–ฅ ์‹คํ–‰๊ฒฐ๊ณผ

java.lang.Object

getName()์€ ํด๋ž˜์Šค ์ด๋ฆ„์„ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.

 

Class#getDeclaredConstructors()

...
Constructor[] constructors = clazz.getDeclaredConstructors();
for(Constructor constructor: constructors) {
    System.out.println(constructor.getName());
}

๐Ÿ–ฅ ์‹คํ–‰๊ฒฐ๊ณผ

java.lang.Object

getDeclaredConstructors()๋Š” ํด๋ž˜์Šค์˜ ๋ชจ๋“  ์ƒ์„ฑ์ž๋ฅผ array๋กœ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค. ์ด๋ ‡๊ฒŒ ๋ฐ˜ํ™˜๋œ Constructor ๊ฐ์ฒด๋ฅผ ์ด์šฉํ•ด ์ƒ์„ฑ์ž์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์œ„ ์ฝ”๋“œ์—์„œ๋Š” Constructor์˜ getName()์„ ์ด์šฉํ•ด์„œ ์ƒ์„ฑ์ž์˜ ์ด๋ฆ„๋งŒ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

 

Class#getMethods()

Method[] methods = clazz.getMethods();
for(Method method: methods) {
    System.out.println(method.getName());
}

๐Ÿ–ฅ ์‹คํ–‰๊ฒฐ๊ณผ

wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll

getMethods()๋Š” ํด๋ž˜์Šค์˜ ๋ชจ๋“  ๋ฉ”์†Œ๋“œ๋ฅผ array๋กœ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. ์ด๋ ‡๊ฒŒ ๋ฐ˜ํ™˜๋œ Method ๊ฐ์ฒด๋ฅผ ์ด์šฉํ•ด ๋ฉ”์†Œ๋“œ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์œ„ ์ฝ”๋“œ์—์„œ๋Š” Method์˜ getName()์„ ์ด์šฉํ•ด์„œ ๋ฉ”์†Œ๋“œ์˜ ์ด๋ฆ„๋งŒ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

 

์ด๋ ‡๊ฒŒ Class ํด๋ž˜์Šค๋Š” ๋ชจ๋“  ๊ฐ์ฒด์— ๋Œ€ํ•œ ๊ฐ์ฒด ์ž์‹ ์˜ ์ •๋ณด ๋“ฑ์„ ์ œ๊ณตํ•˜๋ฉฐ, ์ด๋ฅผ Reflection์ด๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

 

References

์ดˆ๋ณด์ž๋ฅผ ์œ„ํ—Œ Java 200์ œ (2ํŒ)

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€