我无法理解Java注释的默认值。
这是我的密码:
import cn.hutool.core.util.ReflectUtil;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class Question {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Test {
String name = "123";
String name() default name;
}
@Test
private final String demo = null;
public static void main(String[] args) {
System.out.println(System.identityHashCode(Test.name));
System.out.println(System.identityHashCode(
ReflectUtil.getField(Question.class, "demo").getAnnotation(Test.class).name())
);
}
}结果是:
1147985808
1789447862为什么同一个对象的系统hashCode是不同的?
发布于 2022-07-12 16:46:23
这是因为System.identityHashCode()方法不返回实际的哈希码,它只是根据对象类的实现返回哈希码,而不是实际的特定对象。尝试下面,您将看到相同的哈希代码值-
System.out.println(Test.name.hashCode());
System.out.println(ReflectUtil.getField(Question.class, "demo").getAnnotation(Test.class).name().hashCode());此外,要了解更多的信息,请尝试在问题类中重写hashcode方法,如下所示-
public int hashCode(){
return 1;
}然后,当您对任何问题类对象调用hashcode()方法时,它总是给出1,但是System.identityHashCode()方法仍然会给出一些随机值。
https://stackoverflow.com/questions/72949636
复制相似问题