复制代码
class Base { }
class Derived extends Base { }
public class Main {
public static void main(String[] args) {
Base base = new Derived();
if (base instanceof Derived) {
// 这里可以向下转换了
System.out.println("ok");
}
else {
System.out.println("not ok");
}
}
}
RTTI,编译器在编译时打开和检查.class文件
反射,运行时打开和检查.class文件
复制代码
public class Person implements Serializable {
private String name;
private int age;
// get/set方法
}
public static void main(String[] args) {
Person person = new Person("luoxn28", 23);
Class clazz = person.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
String key = field.getName();
PropertyDescriptor descriptor = new PropertyDescriptor(key, clazz);
Method method = descriptor.getReadMethod();
Object value = method.invoke(person);
public class Main {
public static void main(String[] args) {
RealObject real = new RealObject();
Interface proxy = (Interface) Proxy.newProxyInstance(
Interface.class.getClassLoader(), new Class[] {Interface.class},
new DynamicProxyHandler(real));