注解

本文介绍了一个简单的Java程序,演示了如何使用自定义注解来标记类的属性,并通过反射读取这些注解信息。该程序定义了两个自定义注解`@pk`和`@Property`,并展示了如何在`Person`类中应用这些注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package fangfa;

public class Person {
	
	@pk
	int personid;
	
	@Property("PersonName")
String name;
String sex;
public void eat(){
	System.out.println(this.name+"正在吃");
	
}
@Deprecated
public void eat(String food){
	System.out.println(this.name+"正在吃"+food);
	
}
protected void drink(){
	System.out.println(this.name+"正在喝");
}
public Person(String name, String sex) {
	super();
	this.name = name;
	this.sex = sex;
}
public Person() {
	super();
}
private Person(String name) {
	super();
	this.name = name;}
public Person(int personid, String name, String sex) {
	super();
	this.personid = personid;
	this.name = name;
	this.sex = sex;}}

package fangfa;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//此注解是用在属性上,可以存活在运行时
@Target(ElementType.FIELD)//用在属性上
@Retention(RetentionPolicy.RUNTIME)
public @interface pk {
	
}

package fangfa;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)//用在属性上
	@Retention(RetentionPolicy.RUNTIME)
public @interface Property {
	String value();
	//定义的名字和数据库名不一样
	
	
}

package fangfa;

import java.lang.reflect.Field;

public class TestAnnotation {

	/**
	 * @param args
	 */
	@SuppressWarnings("deprecation")
	public static void main(String[] args) {
//	Person p=new Person();
//	p.eat();
//	p.eat("老头包子");

		Class c=Person.class;
		Field[]fs=c.getDeclaredFields();
		for(Field f:fs){
			//是否使用了某个Annptaton
			if(f.isAnnotationPresent(Property.class)){
			//	System.out.println(f.getName());
				
				//获得f这个属性上的Property注解
				Property p=f.getAnnotation(Property.class);
				
			}
		}
		
		
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值