Metaprogramovanie / Anotácie

Sergej Chodarev

Metaprogramovanie 2

Anotácie

Sergej Chodarev

Príklady

@Deprecated
public Integer someOldApi() {
    ...
@SuppressWarnings(value = "unchecked")
void myMethod() 
    ...

Spring

@Autowired
Biker(@Qualifier("bike") Vehicle vehicle) {
    this.vehicle = vehicle;
}
@Configuration
@PropertySource("classpath:/annotations.properties")
@PropertySource("classpath:/vehicle-factory.properties")
class VehicleFactoryConfig {}

Spring MVC

@Controller
@RequestMapping(value = "/vehicles", method = RequestMethod.GET)
class VehicleController {

    @RequestMapping("/home")
    String home() {
        return "home";
    }
}

JetBrains Annotations

public void myMethod(@NotNull Object param) {
    ...
@Contract("null -> false")
public static boolean isNotEmptyString(String str) {
    return str != null && !str.isEmpty();
}

Na čo slúžia anotácie?

Metadáta

Význam metadát

Klasifikácia metadát

Anotácie v Jave

Čo je možné anotovať?

Použitie metadát

Príklady

Príklady

Vlastné anotácie

Anotačný typ

Definícia anotačného typu

Príklad


public @interface Length {
	int min() default 0;
	int max();
}

public class Person {
	@Length(max=30)
	private String name;
	...
}

Meta-anotácie

Reflexia

AnnotatedElement

Príklad

Doplnenie JSON encodera

Riešenie

JsonEncoder (vetva annotations)

Ako to robia iní?

GSON

Verzie

public class VersionedClass {
  @Since(1.1) private final String newerField;
  @Since(1.0) private final String newField;
  private final String field;
  ...

Gson gson = new GsonBuilder().setVersion(1.0).create();

Jackson

@JsonIgnoreProperties({ "extra", "uselessValue" })
public class Value {
  public int value;
}
public class CtorPOJO {
   private final int _x, _y;

   @JsonCreator
   public CtorPOJO(
          @JsonProperty("x") int x,
          @JsonProperty("y") int y) {
      _x = x;
      _y = y;
   }
}
@JsonTypeInfo(use=Id.MINIMAL_CLASS, include=As.PROPERTY,
              property="type")
@JsonSubTypes({@Type(Car.class), @Type(Aeroplane.class)})
public abstract class Vehicle { }
public class Car extends Vehicle {
  public String licensePlate;
}
public class Aeroplane extends Vehicle {
  public int wingSpan;
}
public class PojoWithTypedObjects {
  public List<Vehicle> items;
}
{ "items": [
  { "type": "Car", "licensePlate": "X12345" },
  { "type": "Aeroplane", "wingSpan": 13 }
]}

Alternatívy

Komentáre

/**
 * @ORM\Entity
 * @ORM\Table(name="products") */
class Product{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue */
    protected $id;

Externá konfigurácia

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>

Literatúra

Článok

E. Guerra, M. Cardoso, J. Silva, and C. Fernandes, “Idioms for code annotations in the Java language,” in Proceedings of the 8th Latin American Conference on Pattern Languages of Programs - SugarLoafPLoP’10, 2010 doi: 10.1145/2581507.2581514.