java的注解

//学了很多框架后,一直使用注解,一直明白其中的原理,只知道是用了反射的原理

//今天看了一下,决定很简单。注解为了简化编程,给某个东西起啦个名字,当把这个名字贴到某个地方,这个地方就这个名字的相关意义。

//当你想知道这个地方的相关意义时,你可以通过反射获得该类,然后获得这个名字,通过名字获得这个地方的相关意义。

//下面这篇博客讲的很详细

https://blog.csdn.net/briblue/article/details/73824058

下面是一个小例子:如果你使用过hibernate或者springBoot中使用JPA就很容易理解下面的例子

定义一个table类注解

@Documented

@Retention(RUNTIME)

@Target({ TYPE, FIELD })

public @interface table {

String value(); }

定义了一个culumn注解

@Documented

@Retention(RUNTIME)

@Target({FIELD})

public @interface culumn {

String value(); }

Person类中使用上面两个注解

@table("person")

public class Person {

@culumn("name")

private String name;

@culumn("age")

private String age;

public String getName() {

	return name;
}

public void setName(String name) {

	this.name = name;
	
}

public String getAge() {

	return age;
}
public void setAge(String age) {

	this.age = age;
}

}

下面使用的测试:

public class client {

public static void main(String[] args) {
	try {
	
		String age="23";
		
		String name="dfd";
		
		StringBuffer buffer = new StringBuffer();
		
	Class<Person> o=(Class<Person>) Class.forName("com.mao.Person");
	
	System.out.println(o);
	
	table t= o.getAnnotation(table.class);
	
	buffer.append("select * from "+t.value());
	
	System.out.println(o.getSimpleName());
	
	Field f[]=o.getDeclaredFields();
	
	System.out.println(o.isAnnotationPresent(table.class));
	
	System.out.println(o.getAnnotation(table.class));
	
	culumn a= f[0].getAnnotation(culumn.class);
	
	buffer.append(" where "+a.value()+"="+name);
	
	buffer.append(" and ");
	
    a= f[1].getAnnotation(culumn.class);
	
	buffer.append(a.value()+"="+age);
	
	System.out.println(buffer);
		
	} catch (ClassNotFoundException e) {
	
		e.printStackTrace();
	}

}

}

转载于:https://my.oschina.net/u/2511906/blog/3073059

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值