๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Java

[Java] Reflection์„ ์ด์šฉํ•œ private ์ ‘๊ทผํ•˜๊ธฐ

by cheezzz 2021. 12. 23.
๋ฐ˜์‘ํ˜•

class ๋ฐ–์—์„œ private ํ•จ์ˆ˜๋ฅผ ํ™œ์šฉํ•ด ํ…Œ์ŠคํŠธ๋ฅผ ํ•ด์•ผํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.
public์œผ๋กœ ๋ณ€๊ฒฝํ•˜์ง€ ์•Š๊ณ  Java Reflection์„ ์ด์šฉํ•ด private ํ•จ์ˆ˜์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์„ ๊ตฌํ˜„ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

- Reflection
๊ตฌ์ฒด์ ์ธ ํด๋ž˜์Šค ํƒ€์ž…์„ ์•Œ์ง€ ๋ชปํ•ด๋„, ์—ญ์œผ๋กœ ํด๋ž˜์Šค๋ฅผ ๋™์  ๋กœ๋”ฉํ•˜์—ฌ
ํด๋ž˜์Šค์˜ ๊ตฌ์กฐ๋ฅผ ํ™•์ธํ•˜๊ฑฐ๋‚˜ ์ธํ„ฐํŽ˜์ด์Šค, ๋ฉ”์†Œ๋“œ ๋“ฑ์˜ ์ •๋ณด๋ฅผ ์•Œ์•„๋‚ด์–ด ํ•ด๋‹น ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋ฒ•์ž…๋‹ˆ๋‹ค.

1. import

import java.lang.reflect.Method;


2. Class ๊ฐ์ฒด ์„ ์–ธ

์‚ฌ์šฉํ•  private ํ•จ์ˆ˜๊ฐ€ ์„ ์–ธ๋œ Class ๊ฐ์ฒด๋ฅผ ์„ ์–ธํ•ฉ๋‹ˆ๋‹ค.

TestConfig testConfig = new TestConfig();


3. getDeclaredMethod ์‚ฌ์šฉ
์„ ์–ธํ•œ ๊ฐ์ฒด๋ช….getClass().getDeclaredMethod("์‚ฌ์šฉํ•  ํ•จ์ˆ˜๋ช…", ์‚ฌ์šฉํ•  ํ•จ์ˆ˜์˜ ํŒŒ๋ผ๋ฏธํ„ฐ type class)

Method method = testConfig.getClass().getDeclaredMethod("getDecPwd", String.class);


4. setAccessible
true๋กœ ์„ค์ •

method.setAccessible(true);


5. invoke
return ๊ฐ’์ด Object์ด๊ธฐ ๋•Œ๋ฌธ์— String์œผ๋กœ ๋ณ€ํ™˜ํ•ด์ค๋‹ˆ๋‹ค.
Method๋ช….invoke(์„ ์–ธํ•œ ๊ฐ์ฒด๋ช…, "์‚ฌ์šฉํ•  ํ•จ์ˆ˜์— ์“ฐ์ผ ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฐ’")

String decPwd = (String) method.invoke(testConfig, "ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฐ’");

 

- ์ „์ฒด์ฝ”๋“œ

import java.lang.reflect.Method;

TestConfig testConfig = new TestConfig();
Method method = testConfig.getClass().getDeclaredMethod("getDecPwd", String.class);
method.setAccessible(true);
String decPwd = (String) method.invoke(testConfig, "ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฐ’");

System.out.println(decPwd);

//์ถœ๋ ฅ๊ฐ’ = ๋ณตํ˜ธํ™”๋œ ์•”ํ˜ธ ๊ฐ’ decPwd

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€