开发者

Is there some similar feature in Java as 'attributes' in Delphi?

Is there some similar feature in Java as 'attributes' in Delphi ?

Example explanation of Attribute开发者_如何学运维s in Delphi: http://www.malcolmgroves.com/blog/?p=476

Att.


From that article, you're looking for Java Annotations. They let you do things like:

@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;
    }
}

where @SomeInfo is an annotation. They can be applied to classes, fields, and methods, and they carry metadata about the thing they annotate, which can be read at runtime if they have the appropriate retention. E.g:

@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());
        }
    }
}


It looks like an attributes is a way to store diffrent variable together.

That is what OOP is (Very)generally about (And so is JAVA), creating classes that represents entities. Those entities are basically made of different variables (or attributes)

This example from your link and a comparison to JAVA will make it clearer:

MyAttribute = class(TCustomAttribute)
private
 FName: string;
 FAge: Integer;
public
 constructor Create(const Name : string; Age : Integer);
 property Name : string read FName write FName;
 property Age : Integer read FAge write FAge;
end;

Is just like a little class in JAVA:

public class Customer()
{
  String Fname;
  int FAge;

  public Customer()
  {
   /*constructor code*/
  }
}

and creating the class from your example:

  TMyClass = class
 public
  [MyAttribute('Malcolm', 39)]

Is just like creating a new person object:

Customer[] cust1= new Customer['Malcolm', 39]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜