Friday, 18 March 2022

Check whether a field is annotated with given annotation or not

Using 'isAnnotationPresent' method of Field object, we can check whether an annotation for the specified type is present on this element or not.

 

Signature

public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)

 

Example

field.isAnnotationPresent(Deprecated.class)

 Above snippet return true, if the field is annotated with @Deprecated, else false.

 

 


Find the below working application.

 

ChatServer.java

package com.sample.app;

public class ChatServer {

	@Deprecated
	private int connectionTimeout;
	private int bufferSize;

	public ChatServer(int connectionTimeout, int bufferSize) {
		this.connectionTimeout = connectionTimeout;
		this.bufferSize = bufferSize;
	}

	public int getConnectionTimeout() {
		return connectionTimeout;
	}

	public void setConnectionTimeout(int connectionTimeout) {
		this.connectionTimeout = connectionTimeout;
	}

	public int getBufferSize() {
		return bufferSize;
	}

	public void setBufferSize(int bufferSize) {
		this.bufferSize = bufferSize;
	}

}

FieldAnnotationCheck.java

package com.sample.app;

import java.lang.reflect.Field;

public class FieldAnnotationCheck {
	
	public static void main(String[] args) {
		ChatServer chatServer = new ChatServer(10000, 25000);
		
		Field[] fields = chatServer.getClass().getDeclaredFields();
		for(Field field: fields) {
			if(field.isAnnotationPresent(Deprecated.class)) {
				System.out.println(field.getName() + " is depreacted");
			}
		}
		
	}

}

Output

connectionTimeout is deprecated







 

Previous                                                    Next                                                    Home

No comments:

Post a Comment