是个强大的工具,动态运行,runtime初学,感知力不强,等待后面的我补充

  • Analyze the capabilities of classes at runtime
  • Inspect objects at runtime—for example, to write a single toString method that works for all classes
  • Implement generic array manipulation code
  • Take advantage of Method objects that work just like function pointers in languages such as C++

The Class Class

Employee e;
Class cl0 = e.getClass();
Class cl1 = Class.forName("java.util.Random");
Class cl2 = Random.class;
 
System.out.println(e.getClass().getName() + " " + e.getName());

可以写出这样的代码,来记录对象的类。getName 来获取类名。可以通过实例找类,也可以通过字符串找类

由于加载一个方法会递归地加载这个方法内用到的其他类,导致启动很慢。因此可以不让 main explicitly 使用别的类,而是通过 Class.forName 来实现

实际上 Class 也是一个泛型,但是写的时候没体现,咱也别在意了

if (e.getClass() == Employee.class)
if (e instanceof Employee)

each Class object for each type 是独一无二的,所以可以直接 == 判断。两者区别在于继承关系能否体现

C++ Note review

The newInstance method corresponds to the idiom of a virtual constructor in C++. However, virtual constructors in C++ are not a language feature but just an idiom that needs to be supported by a specialized library. The Class class is similar to the type_info class in C++, and the getClass method is equivalent to the typeid operator. The Java Class is quite a bit more versatile than type_info, though. The C++ type_info can only reveal a string with the name of the type, not create new objects of that type.

Resources

Class cl = ResourceTest.class;
URL aboutURL = cl.getResource("about.gif");

有些类会用到外部资源,可以利用 Class 定位,同时打包 JAR

Reflection 来好好处理 Class

Reflection 来好好处理 Object

初学感觉一堆脱裤子放屁的操作

var harry = new Employee("Harry Hacker", 50000, 10, 1, 1989); 
Class cl = harry.getClass();
Field f = cl.getDeclaredField("name");
f.setAccessible(true); // now OK to call f.get(harry)
Object v = f.get(harry);
// the String object "Harry Hacker"

千里迢迢来访问 fields of object。该不能访问还是不能访问,该警告还是警告,想要不警告不报错,可以考虑采用 variable handle

可以用来写任意类的 toString 方法,不脱裤子放屁的点在于他可以无视名字,不需要名字,获取所有的 fields

Reflection 来帮助写泛型方法

调用任意的 Methods & Constructor

可以模仿 C/C++ 的函数指针。但是设计者认为这是不好的风格,interfacelambda expression是其上位

Method

类似 field.get(obj),有 method.invoke(obj, args) 的用法

method 获取的方法自然是 getMethod,其中,静态方法没有对象,给 null 就行

Method m1 = Employee.class.getMethod("getName"); 
Method m2 = Employee.class.getMethod("raiseSalary", double.class);

一个方法的 signature 包含名字和参数,所以这里也需要给出

Constructor

constructor 就是 getConstructor 配合 newInstance

Class cl = Random.class; // or any other class with a constructor that accepts a long parameter 
Constructor cons = cl.getConstructor(long.class); 
Object obj = cons.newInstance(42L);

⚠️ 最终作者也建议你用上位,呵呵,白学了