Skip to content

Instantly share code, notes, and snippets.

@Host32
Last active August 15, 2016 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Host32/3afbe9fcd7f5e75d5b2a50f1ef62486d to your computer and use it in GitHub Desktop.
Save Host32/3afbe9fcd7f5e75d5b2a50f1ef62486d to your computer and use it in GitHub Desktop.
Java Annotations, que bruxaria é essa?
public @interface Printable {
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Printable {
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Printable {
String label();
}
import java.lang.reflect.Method;
import java.util.List;
public class Printer {
public void print(List<User> users) {
System.out.println("Listagem de usuários:");
try {
for (User user : users) {
StringBuilder userData = new StringBuilder();
for (Method method : user.getClass().getDeclaredMethods()) {
if (method.isAnnotationPresent(Printable.class)) {
Printable printableMeta = method.getAnnotation(Printable.class);
userData.append(printableMeta.label()).append(": ").append(method.invoke(user)).append(", ");
}
}
System.out.println(userData.toString());
}
} catch (Exception e) {
System.err.println("Error!");
}
}
}
public class User {
// atributos e construtores omitidos
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public String getEmail(){
return this.email;
}
public String getPassword(){
return this.password;
}
}
public class User {
// atributos e construtores omitidos
@Printable(label = "Nome")
public String getName(){
return this.name;
}
@Printable(label = "Idade")
public int getAge(){
return this.age;
}
@Printable(label = "Email")
public String getEmail(){
return this.email;
}
public String getPassword(){
return this.password;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment