Showing posts with label annotations. Show all posts
Showing posts with label annotations. Show all posts

Sunday, 20 March 2022

Java: How to check whether given class is an annotation or not?

'java.lang.Class' provides 'isAnnotation' method which return true, if the given class is an annotation, else false.

 

ClassAnnotationCheck.java

package com.sample.app;

public class ClassAnnotationCheck {
	
	public static void main(String[] args) {
		System.out.println("Is System class represent an annotation : "+ System.class.isAnnotation());
		System.out.println("Is Deprecated class represent an annotation : "+ Deprecated.class.isAnnotation());
	}

}

Output

Is System class represent an annotation : false
Is Deprecated class represent an annotation : true



 

  

Previous                                                    Next                                                    Home

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

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

Friday, 14 January 2022

Define custom Jackson annotation using @JacksonAnnotationsInside

You can define custom Jackson annotation using @JacksonAnnotationsInside. @JacksonAnnotationsInside is a meta-annotation used to create a "combo-annotations" by having a container annotation, which needs to be annotated with this annotation as well as all annotations it 'contains'.

Example



Find the below working application. 

AppJSON.java

package com.sample.app.jackson;

import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;

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

import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;

@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonAutoDetect(getterVisibility = PUBLIC_ONLY, setterVisibility = PUBLIC_ONLY, fieldVisibility = NONE)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonIgnoreProperties(ignoreUnknown = true)
public @interface AppJSON {
	
}

Employee.java

package com.sample.app.model;

import com.sample.app.jackson.AppJSON;

@AppJSON
public class Employee {
	private Integer id;
	private String name;
	private Integer age;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

}

App.java

package com.sample.app.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sample.app.model.Employee;

public class App {

	public static void main(String args[]) throws JsonProcessingException {
		Employee emp = new Employee();
		emp.setId(1);
		emp.setName("Krishna");
		
		String result = new ObjectMapper().writeValueAsString(emp);
		System.out.println(result);
	}
}

Output

{"id":1,"name":"Krishna"}


Previous                                                    Next                                                    Home

Saturday, 19 June 2021

Junit 5: Jupiter core annotations

org.junit.jupiter.api package contains core annotations. Below table summarizes the core annotations of junit 5 jupiter.

 

Annotation

Description

AfterAll

@AfterAll is used to signal that the annotated method should be executed after all tests in the current test class.

AfterEach

@AfterEach is used to signal that the annotated method should be executed after each @Test, @RepeatedTest, @ParameterizedTest, @TestFactory, and @TestTemplate method in the current test class.

BeforeAll

@BeforeAll is used to signal that the annotated method should be executed before all tests in the current test class.

BeforeEach

@BeforeEach is used to signal that the annotated method should be executed before each @Test, @RepeatedTest, @ParameterizedTest, @TestFactory, and @TestTemplate method in the current test class.

Disabled

@Disabled is used to signal that the annotated test class or test method is currently disabled and should not be executed.

DisplayName

@DisplayName is used to declare a custom display name for the annotated test class or test method.

DisplayNameGeneration

@DisplayNameGeneration is used to declare a custom display name generator for the annotated test class.

Nested

@Nested is used to signal that the annotated class is a nested, non-static test class (i.e., an inner class) that can share setup and state with an instance of its enclosing class.

Order

@Order is an annotation that is used to configure the order in which the annotated element (i.e., field or method) should be evaluated or executed relative to other elements of the same category.

RepeatedTest

@RepeatedTest is used to signal that the annotated method is a test template method that should be repeated a specified number of times with a configurable display name.

Tag

@Tag is a repeatable annotation that is used to declare a tag for the annotated test class or test method.

Tags

@Tags is a container for one or more @Tag declarations.

Test

@Test is used to signal that the annotated method is a test method.

TestFactory

@TestFactory is used to signal that the annotated method is a test factory method.

TestInstance

@TestInstance is a type-level annotation that is used to configure the lifecycle of test instances for the annotated test class or test interface.

TestMethodOrder

@TestMethodOrder is a type-level annotation that is used to configure a MethodOrderer for the test methods of the annotated test class or test interface.

TestTemplate

@TestTemplate is used to signal that the annotated method is a test template method.

Timeout

@Timeout is used to define a timeout for a method or all testable methods within one class and its @Nested classes.


You can download complete working applications from this link.

https://github.com/harikrishna553/junit5/tree/master/junit5-examples

Previous                                                    Next                                                    Home

Sunday, 8 March 2020

TestNG: Basic Annotations


Previous                                                    Next                                                    Home