Item 65. Reflection & Interface
μ νλ ννμ 리νλ μ
μ¬μ©
class Example {
public static void main(String[] args) {
// ν΄λμ€ μ΄λ¦μ Class κ°μ²΄λ‘ λ³ν
Class<? extends Set<String>> cl = null;
try {
// λΉκ²μ¬ νλ³ν
cl = (Class<? extends Set<String>>) Class.forName("java.util.TreeSet");
} catch (ClassNotFoundException e) {
fatalError("ν΄λμ€λ₯Ό μ°Ύμ μ μμ΅λλ€.");
}
// μμ±μλ₯Ό μ»μ
Constructor<? extends Set<String>> cons = null;
try {
cons = cl.getDeclaredConstructor();
} catch (NoSuchMethodException e) {
fatalError("λ§€κ°λ³μ μλ μμ±μλ₯Ό μ°Ύμ μ μμ΅λλ€.");
}
// μ§ν©μ μΈμ€ν΄μ€ μμ±
Set<String> s = null;
try {
s = cons.newInstance();
} catch (ReflectiveOperationException e) {
fatalError("리νλ μ
μμΈ λ°μ");
}
// μμ±ν μ§ν© μ¬μ©
String[] a = {"a", "b", "c"};
s.addAll(Arrays.asList(a).subList(0, a.length));
System.out.println(s);
}
private static void fatalError(String msg) {
System.err.println(msg);
System.exit(1);
}
}Last updated