Session 14
Session 14
y
nl
O
se
U
tre
Annotations and Base64 Encoding
en
C
h
ec
pt
rA
Fo
y
nl
O
se
Explain declaring an annotation type in Java
U
Describe predefined annotation types
tre
Explain Type annotations
Explain Repeating annotations
en
Describe Base64 encoding
C
h
ec
pt
rA
Fo
y
nl
Annotation:
O
se
As the name implies, is a syntactic metadata
U
that are added to the Java source.
tre
en
Is a specific part of the original source,
C
however, does not affect the operation of the
h
code.
ec
pt
rA
Fo
y
Following elements are annotated in Java:
nl
O
se
U
Tables Methods
tre
en
C
Variables Classes
h
ec
pt
rA
Parameters
Fo
y
nl
An enhanced feature is introduced in Java 8 called Pluggable Annotation Processing API.
O
se
Write a customized
U
Annotation Processor
tre
en
API helps to
C
h
Code dynamically to
y
nl
O
se
U
tre
Information for the Runtime
en
Documentation Code Generation
Compiler Processing
C
h
ec
pt
rA
Fo
y
To declare an annotation, prefix with @ as follows:
nl
O
Syntax:
se
@<name>
U
@<name>
tre
en
Example:
Here, @(at)symbol signals to the compiler that this is an annotation
C
h
@Item
ec
pt
rA
y
Following are three built-in annotations:
nl
O
se
U
@Deprecated
tre
en
C
h
ec
@Override
@Suppress
pt
Warnings
rA
Fo
y
nl
O
@SuppressWarnings
@Deprecate
@Override
Annotation Creates a compile Can compress
se
deprecates a time check compiler
class, method, or warnings
U
field
tre
en
C
h
ec
pt
rA
Fo
y
Predefined annotations are demonstrated through following codes:
nl
O
se
@Override
@Deprecate @SuppressWarnings
U
public class ClassOne
@Deprecated {
tre
public class public void show (String testmsg){
SampleContent { System.out.println(testmsg);
en
} } @SuppressWarnings
public class Test { public static void main(String args[]){ public void alertMethod() {
C
public static void SubClass obj = new SubClass(); }
main(String args[]){ obj.show ("Good day!!");
@SuppressWarnings("unmarked")
h
SampleContent c = new }
@SuppressWarnings({"unmarked",
ec
SampleContent(); }
… class SubClass extends ClassOne "deprecation"})
{
pt
}
} @Override
rA
}
}
© Aptech Ltd. Fundamental Programming in Java -Session 14 / Slide 10
Predefined Annotations 4/4
y
There are two advantages of using @Override annotation:
nl
O
If a programmer makes any unintentional error while overriding,
se
then it results in a compile time error. Using @Override instructs
U
tre
compiler that it is overriding this method.
en
It helps to enhance code readability.
C
h
ec
pt
rA
Fo
y
Custom Annotations created in Java are defined in their own files.
nl
O
se
@interface SampleAnnotate{
String samplValue();
U
String name();
int age();
tre
String[] addNames();
en
}
C
h
ec
pt
rA
Fo
y
Custom Annotations uses following syntax:
nl
O
se
@Retention @Target @Inherited @Documented
U
tre
import import
@Retention(RetentionPolic @Target({ElementType.METH
java.lang.annotation.Inhe java.lang.annotation.Docu
y.RUNTIME) OD})
en
rited; mented;
@interface SampleAnnotate public @interface
@Inherited @Documented
{ SampleAnnotate{...
public @interface @interface TestAnnotate {
C
... }
SampleAnnotate { . . .
} }
} @SampleAnnotate
h
class Person { ... } @TestAnnotate
y
nl
O
• For example, to ensure that a variable in program is never assigned to null or to avoid triggering a
NullPointerException, a custom plugin can be written.
se
U
• Then, modify code to annotate variable specifying that it is never assigned to null.
tre
• Following syntax shows the variable declaration:
en
@NonNull String str;
C
h
Here,
ec
str is a String variable in the annotation.
pt
rA
Compiler shows a warning if it notices a potential problem, allowing you to modify the code to avoid the error while
calculating the NonNull module at the command line during code compilation. After editing the code to remove all
Fo
warnings, this specific error will not occur when the program runs.
y
nl
Helps to apply the same annotations at multiple times for the same declaration.
O
se
@ScoreSchedule(dayOfMonth="last")
U
@ScoreSchedule(dayOfWeek="Wed", hour="21")
tre
public void scorePapers() { ... }
en
C
Here, the annotation @ScoreSchedule has been applied twice, thus, it is a repeating
h
annotation. Repeating annotations can be applied not only to methods also to any item
that can be annotated. ec
pt
rA
Fo
y
nl
Java compiler.
O
For the compiler to perform this, two declarations are necessary in the code:
se
U
1) Declare a Repeatable Annotation type.
tre
/*
en
*Aptech Java8
*Java tester
C
*/
import java.lang.annotation.Repeatable;
h
ec
@Repeatable(ScoreSchedules.class)
public @interface ScoreSchedule {
pt
String monthDay() default "1st";
rA
y
nl
public @interface ScoreSchedules {
O
ScoreSchedule[] value();
se
}
U
tre
Here, ScoreSchedules is the class for @interface annotation.
en
C
h
ec
pt
rA
Fo
y
nl
O
import java.lang.annotation.Repeatable;
@Repeatable(ScoreSchedules.class)
se
@interface ScoreSchedule {
String monthDay() default "1st";
U
String weekDay() default "Monday";
tre
int hour() default 12;
}
en
@interface ScoreSchedules {
ScoreSchedule[] value();
C
}
h
public class RepeatingDemo {
ec
public static void main(String args[]){}
@ScoreSchedule(monthDay="last")
pt
@ScoreSchedule(weekDay="Fri", hour=23)
rA
y
nl
Reflection API of Java can be used to access annotations on any type such as class or interface or
O
methods.
se
Several methods in Reflection API help to retrieve annotations.
U
tre
Methods that generate a single annotation, such as
AnnotatedElement.getAnnotationByType (Class <T>) remain unchanged.
en
C
They return only a single annotation when one annotation of the requisite type is available.
h
ec
If one or more annotation of the required type is available, it can be acquired by getting the
pt
container annotation.
rA
Fo
y
import java.lang.reflect.ParameterizedType;
nl
import java.lang.reflect.WildcardType;
import java.util.List;
O
public class SampleRefl {
se
public static void main(String[] args)
throws NoSuchMethodException, SecurityException {
U
Method sampMeth = SampleRefl.class.getMethod("sampMeth", List.class);//here Method defined as sampMeth
ParameterizedType sampleLiTy = (ParameterizedType)sampMeth. getGenericParameterTypes()[0];//here List Type
tre
//defined as SampleLiTy
ParameterizedType sampleClTy = (ParameterizedType)sampleLiTy. getActualTypeArguments()[0];//here Class Type
en
//defined as SampleClTy
WildcardType sampleGenTy = (WildcardType)sampleClTy. getActualTypeArguments()[0];//here generic Type
//defined as SampleGenTy
C
Class<?> SampleGenCl = (Class<?>)sampleGenTy.getUpperBounds()[0];// here generic Class defined as sampleGenCl
boolean isException = Exception.class. isAssignableFrom(SampleGenCl);
h
//to display whether the statement is true or false
ec
System.out.println("This Class extends RuntimeException: " + isException);
boolean isRuntimeException = RuntimeException.class. isAssignableFrom(SampleGenCl);
pt
// to display whether the statement is true or false"
rA
}
}
© Aptech Ltd. Fundamental Programming in Java -Session 14 / Slide 20
Processing Annotations Using Reflection 3/4
y
nl
Output:
O
se
This Class extends RuntimeException:true
U
This Class extends RuntimeException:false
tre
en
C
Here, SampleGenCl class is reflected through sampMeth()method.
h
ec
pt
rA
Fo
y
nl
@Functional Interface:
O
The annotated element will operate as a functional interface and compiler generates an error if the element
se
does not comply with the requirements.
U
tre
en
@FunctionalInterface
interface MyCustomInterface
C
{
h
....}
ec
pt
rA
Fo
y
nl
Used for purposes such as:
O
se
Unit testing
U
Code quality analysis
tre
XML parsing
Dependency injection
en
C
h
ec
pt
rA
Fo
y
nl
O
Three types of Base64 encoding:
se
U
• Output is limited to a set of characters between A-Z, a-z, 0-9,
tre
Simple and +.
en
C
• The final output is safe from filename and URL and is limited
URL
h
to a set of characters between A-Z, a-z, 0-9, and +_.
ec
pt
rA
y
Two nested classes in Base64:
nl
O
se
U
tre
en
C
h
ec
pt
rA
Fo
Methods:
y
nl
static Base64.Decoder getDecoder()
O
se
static Base64.Encoder getEncoder()
U
tre
getMimeDecoder()
en
getMimeEncoder()
C
h
ec
getMimeEncoder(intlineLength, byte[] lineSeparator)
pt
getUrlDecoder()
rA
Fo
getUrlEncoder()
© Aptech Ltd. Fundamental Programming in Java -Session 14 / Slide 26
Base64 (java.util.Base64) Encoding 4/5
Following code encodes a string to base64, then decode the same String back to a base64 encoded output
y
nl
stream:
import java.util.Base64;
O
import java.util.UUID;
import java.io.UnsupportedEncodingException;
se
/**Aptech Java
*Base64 example in detail
*/
U
public class HelloWorld {
public static void main(String args[]){
tre
try {
// Encoding a string using Base64
String sampleBase64EncoStr = Base64.getEncoder(). encodeToString("AptechJava8".getBytes("utf-8"));
en
System.out.println("Encoded String (Basic) looks like this: " + sampleBase64EncoStr);
// Decoding a string using Base64
C
byte[] base64decodedBytes = Base64.getDecoder(). decode(sampleBase64EncoStr);
System.out.println("Decoded String is : " + new String(base64decodedBytes, "utf-8"));
sampleBase64EncoStr = Base64.getUrlEncoder(). encodeToString("AptechJava8".getBytes("utf-8"));
h
System.out.println("Encoded String (URL)looks like this: " + sampleBase64EncoStr);
ec
StringBuilder strBuild = new StringBuilder();
for (int j = 0; j < 10; ++j) {
pt
strBuild.append(UUID.randomUUID().toString());
}
rA
y
Output:
nl
O
Encoded String (Basic) looks like this: QXB0ZWNoSmF2YTg=
Decoded String is: AptechJava8
se
Encoded String (URL) looks like this: QXB0ZWNoSmF2YTg=
U
Encoded String (MIME) look like this:
YzNlNmYyNjctY2JkNi00OTFiLThiMzQtZTMwZTJkZjBkZTU2YTljM2FlN2YtZTJlMi00YmVlLWI2
tre
NDQtNjFjMGZiYmI4NDc5NWFmOTA3YjktYTc5Ni00MDBkLTg2ZjItOTllOGRhMDJkODE4YmZmZmYx
YzQtNjA1Yy00M2ZhLWJkNTMtNzEwOWI5NzYwMGY4NGE0YTZkZjUtZWQ5Zi00NWY0LWE3YTAtYmZi
en
MDU5MWRjMGM2OWVjOTYyNDEtZGU1Yi00YWFiLTllMmYtM2MyYjg3MjY4ZTYzNDg0MGMzYzctZjEy
C
MS00OTJiLThjM2MtZTQxMDExNmQzM2RlMDdlYjMyNTYtNmI2Mi00NjVmLTgyYzItOWY5OGQ3OTdh
ZmJlMzJiYzNhNWEtZmM1Mi00ZmI1LTg5NDAtZjdjZGJjOWFhYWVjNTg4Y2YxODktYjk2NC00YTJk
h
LTlhMWYtYmNmNGRmOTQ5MTI4
ec
pt
rA
Fo
y
Annotations are comments, notes, remarks, or explanations. In Java,
nl
annotations help to associate these additional information (also called
O
metadata) to the program elements. Annotations can be determined from
se
source files or class files at runtime.
U
The @Deprecated annotation is used for deprecating or marking a class,
method or field as deprecated, signifying that the part of code no longer will
tre
no longer be used.
en
The @SuppressWarnings annotation can suppress the compiler warnings in
any available method.
C
Since, annotation types are piled up and stored in byte code files such as
h
classes, the annotations reverted by these methods can be enquired as any
systematic Java object. ec
pt
Base64 encoding has an in-built encoder and a decoder. In Java 8, there are
rA