gpt4 book ai didi

java - Java 中是否有与 Delphi 中的 'attributes' 类似的功能?

转载 作者:行者123 更新时间:2023-11-29 06:08:59 26 4
gpt4 key购买 nike

Java 中是否有与 Delphi 中的“属性”类似的功能?

Delphi中Attributes的例子解释: http://www.malcolmgroves.com/blog/?p=476

注意

最佳答案

从那篇文章中,您正在寻找 Java Annotations .他们让你做这样的事情:

@SomeInfo(author = "Bob", year = 1993)
class Foo {
@SomeInfo(author = "me", somethingElse = "abcdefg")
private int x = 5;

@SomeInfo(author = "Fred", column = "order")
public int getX() {
return x;
}
}

其中 @SomeInfo 是一个注解。它们可以应用于类、字段和方法,并且它们携带有关它们注释的事物的元数据,如果它们具有适当的保留,则可以在运行时读取这些元数据。例如:

@Retention(RetentionPolicy.RUNTIME)
@interface SomeInfo {
String author();
int year() default -1;
String column() default "";
String somethingElse() default "";
}

class Main {
public static void main(String[] args) throws Exception {
List<AnnotatedElement> annotatedElements =
new ArrayList<AnnotatedElement>();
annotatedElements.add(Foo.class);
annotatedElements.add(Foo.class.getDeclaredField("x"));
annotatedElements.add(Foo.class.getDeclaredMethod("getX"));
for (AnnotatedElement annotatedElement : annotatedElements) {
System.out.println("Author of {" + annotatedElement + "} = " +
annotatedElement.getAnnotation(SomeInfo.class).author());
}
}
}

关于java - Java 中是否有与 Delphi 中的 'attributes' 类似的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7669505/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com