Item 53: Prefer interfaces to reflection
Disadvantages of reflection:
Writing a program with classes unknown at compile time:

Prefer interfaces to reflection. (Item 53)

1. Item 53: Prefer interfaces to reflection

2. Disadvantages of reflection:

• No compile-time type checking
• Bad readability of a code
• Performance suffers

3. Writing a program with classes unknown at compile time:

• Use reflection only to instantiate objects
• Access the objects using some interface or superclass that is known at
compile time

4.

// Reflective instantiation with interface access
public static void main(String[] args) {
// Translate the class name into a Class object
Class<?> cl = null;
try {
cl = Class.forName(args[0]);
} catch (ClassNotFoundException e) {
System.err.println("Class not found.");
System.exit(1);
}
// Instantiate the class
Set<String> s = null;
try {
s = (Set<String>) cl.newInstance();
} catch (IllegalAccessException e) {
System.err.println("Class not accessible.");
System.exit(1);
} catch (InstantiationException e) {
System.err.println("Class not instantiable.");
System.exit(1);
}
// Exercise the set
s.addAll(Arrays.asList(args).subList(1, args.length));
System.out.println(s);
}
English     Русский Правила