this is my code:
@Column(columnName="firstname")
private String firstName;
@Column(columnName="lastname")
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
is it possible to read the value of my annotation @Column(columnName="xyz123") in another class?
In common case you have private access for fields, so you CAN'T use getFields in reflection. Instead of this you should use getDeclaredFields
So, firstly, you should be aware if your Column annotation has the runtime retention:
After that you can do something like this:
Obviously, you would like to do something with field - set new value using annotation value:
So, full code can be looked like this:
Yes, if your Column annotation has the runtime retention
you can do something like this
UPDATE : To get private fields use
Of course it is. Here is a sample annotation:
And a sample annotated method:
And a sample method in another class that prints the value of the testText:
Not much different for field annotations like yours.
Cheerz!
You can also use generic types, in my case, taking into account everything said before you can do something like:
Remember, that this will not equival at 100% to SomeClass.class.get(...)();
But can do the trick...
I've never done it, but it looks like Reflection provides this.
Field
is anAnnotatedElement
and so it hasgetAnnotation
. This page has an example (copied below); quite straightforward if you know the class of the annotation and if the annotation policy retains the annotation at runtime. Naturally if the retention policy doesn't keep the annotation at runtime, you won't be able to query it at runtime.An answer that's since been deleted (?) provided a useful link to an annotations tutorial that you may find helpful; I've copied the link here so people can use it.
Example from this page:
Elaborating to the answer of @Cephalopod, if you wanted all column names in a list you could use this oneliner: