* @return The {@code Class} object that represents the runtime * classofthisobject. publicfinalnativeClass<?> getClass();
从源码中可以看到 getClass 是 final 方法,无法被继承。同时是 native 方法。即其他语言例如 C 与 C++ 实现的方法。结果为对象的运行时 Class 对象。
举个例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
package im.yfd.demo; classA{ }
classBextendsA{ }
classTest{ publicstaticvoidmain(String[] args){ A a = new A(); A b = new B(); System.out.println(a.getClass()); System.out.println(b.getClass()); a = b; System.out.println(a.getClass()); } }
publicclassPerson{ Person(String name) { this.name = name; } private String name; @Override publicbooleanequals(Object object){ if (this == object) { returnfalse; } if (object == null || object.getClass() != this.getClass()) { returnfalse; } Person p = (Person) object; if (p.name == null) { returnthis.name == null; } return p.name.equals(this.name); } }
classTest{ publicstaticvoidmain(String[] args)throws CloneNotSupportedException { Person a = new Person("name"); Person b = new Person("name"); Map<Person, String> map = new HashMap<>(); map.put(a, "a"); System.out.println(a.equals(b)); System.out.println(map.get(a)); System.out.println(map.get(b)); } }
class Test { public static void main(String[] args) throws CloneNotSupportedException { Test test = new Test(); Test testClone = (Test) test.clone(); } }
会报错 Exception in thread "main" java.lang.CloneNotSupportedException。
publicstaticvoidmain(String[] args)throws CloneNotSupportedException { Test test = new Test(); test.name = "1"; System.out.println("test 1"); System.gc(); test = new Test(); System.gc(); System.out.println("test 2"); } }