import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.CONSTRUCTOR) //约束条件。只能限定注解构造函数。
@Retention(value = RetentionPolicy.RUNTIME) //运行时。
public @interface Info {
int id() default 0;
String name() default "zhang";
String password() default "123";
}
public class User {
@Info(id = 1, name = "zhangphil", password = "123456")
public User () {
}
}
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import java.lang.reflect.Constructor;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Constructor[] constructors = User.class.getConstructors();
for (Constructor constructor : constructors) {
if (constructor.isAnnotationPresent(Info.class)) {
Info info = (Info) constructor.getAnnotation(Info.class);
System.out.println(info.id());
System.out.println(info.name());
System.out.println(info.password());
}
}
}
}
输出: