Sunday, 20 March 2022

Java: Get the annotation details present on a class

'java.lang.Class' provides 'getAnnotation' method, which returns this element's annotation for the specified type if such an annotation is present, else null.

 

Signature

public <A extends Annotation> A getAnnotation(Class<A> annotationClass)

Example

AppConfiguration appConfiguration = ChatServer.class.getAnnotation(AppConfiguration.class);

Above snippet return the reference of annotation AppConfiguraiton if the class ChatServer is annotated with it, else null.



Find the below working application.

 

AppConfiguration.java
package com.sample.app;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(value = ElementType.TYPE)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface AppConfiguration {

	String filePath() default "appConfig";

	String contentType() default "json";

}

ChatServer.java

package com.sample.app;

@AppConfiguration(filePath = "/Users/krishna/app/config.json", contentType = "application/json")
public class ChatServer {

	private Integer connectionTimeout;
	private int bufferSize;

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

	public Integer getConnectionTimeout() {
		return connectionTimeout;
	}

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

	public int getBufferSize() {
		return bufferSize;
	}

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

}

 

GetAnnotationsDefinedOnClass.java

package com.sample.app;

public class GetAnnotationsDefinedOnClass {

	public static void main(String[] args) {

		AppConfiguration appConfiguration = ChatServer.class.getAnnotation(AppConfiguration.class);

		if (appConfiguration == null) {
			System.out.println("Class is not anotated with given annotation");
			return;
		}

		String filePath = appConfiguration.filePath();
		String contentType = appConfiguration.contentType();

		System.out.println("filePath : " + filePath);
		System.out.println("contentType : " + contentType);

	}

}

Output

filePath : /Users/krishna/app/config.json
contentType : application/json

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment