¸Å°³º¯¼ö ÀÖ´Â ¸Þ¼µå¸¦ È£ÃâÇØ º¸¾Ò´Ù¸é ´ÙÀ½ ¿¹Á¦´Â ³Ê¹«³ª ½±°Ô ÀÌÇØ ÇÏ½Ç ¼ö ÀÖ½À´Ï´Ù. ¸Å°³º¯¼öÀÚ¸®¿¡ null°ª¸¸ ÀÔ·ÂÇÏ¸é µÇ´Ï±î ±×·¸°Ô ¾î·ÆÁö´Â ¾Ê½À´Ï´Ù. ¾Æ·¡ÀÇ ¿¹Á¦´Â StringŬ·¡½ºÀÇ ¸â¹ö¸Þ¼µåÀÎ length¸Þ¼µå¸¦ È£ÃâÇϰí ÀÖ½À´Ï´Ù.
n String s = new String(¡°Hello World¡±);
n int r=s.length();
n °á°ú:11
ÀÇ ±¸¹®À» ¸®Ç÷º¼ÇÀÇ ±â¹ýÀ» ÀÌ¿ëÇÏ¿© ´Ù½Ã ¸¸µç ¿¹Á¦ÀÔ´Ï´Ù.
MethodInvoke2.java(¸Å°³º¯¼ö ¾ø´Â ¸Þ¼µå È£ÃâÇϱâ) |
import java.awt.*; import java.lang.reflect.*; public class MethodInvoke2{ public static void main(String[] arg) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { Class c = String.class; Method m = c.getMethod("length", null); String s = "Hello World"; Object result = m.invoke(s, null); System.out.println(result.toString()); } } |
C:\JavaExample\11>javac MethodInvoke2.java C:\JavaExample\11>java MethodInvoke2 11 |
À§ÀÇ ¿¹Á¦¿¡¼ ÀÓÀÇÀÇ Class c¿¡¼ ÀÚ½ÅÀÌ È£ÃâÇϰíÀÚ ÇÏ´Â ¸Þ¼µå¸¦ ã°í ÀÖ½À´Ï´Ù. ÀÌ ¶§ ¸Å°³º¯¼ö°¡ ÇÊ¿ä ¾ø±â ¶§¹®¿¡ ¸Å°³º¯¼öÀÚ¸®¿¡ null¸¸À» ±âÀÔÇÏ¸é ¿øÇÏ´Â ¸Þ¼µå °´Ã¼¸¦ ¾òÀ» ¼ö ÀÖ½À´Ï´Ù.
n Method m = c.getMethod("length", null);
±×¸®°í °´Ã¼ sÀÇ ¸Þ¼µå¸¦ Method mÀ» ÅëÇØ¼ È£ÃâÇÏ¸é µË´Ï´Ù.
n String s = "Hello World";
n Object result = m.invoke(s, null);
°á°ú·Î ³ª¿Â result°´Ã¼´Â ¹°·Ð IntegerÇüÀÇ °´Ã¼À̱⠶§¹®¿¡ printlnÀ» ÇØº¸¸é ´ç¿¬È÷ ¡°Hello World¡±ÀÇ ¹®ÀÚ¿ÀÇ ±æÀÌÀÎ 11ÀÌ Ãâ·ÂµÇ°Ô µË´Ï´Ù.
jabookÀúÀÚ¸íÇÔ |
Á¦¸ñ:¼Ò¼³°°ÀºÀÚ¹Ù3ºÎ ÀúÀÚ:ÃÖ¿µ°ü |