Advanced Java - Exceptions, Annotations, Basics of Reflections
Advanced Java - Exceptions, Annotations, Basics of Reflections
ANNOTATIONS, BASICS OF
REFLECTIONS
EXCEPTIONS
JAVA EXCEPTION
Exceptions in Java are special objects derived from
the Throwable class, which, apart from standard
operations on objects, can also be thrown using the
throws keyword, which causes an immediate
termination of the thread and goes to the first
encountered place that this exception can handle .
values.add("Jan");
try {
System.out.printf("Value at index
3: %d\n",values.get(3));
}catch (IndexOutOfBoundsException e)
{
System.out.println("No value at
index");
}</string>
TRY
Block within which an exception can be thrown.
try {
System.out.printf("Value at index 3:
%d\n",values.get(3));
}
CATCH
The try block must be bound to the catch block,
which is responsible for handling the exception.
catch (IndexOutOfBoundsException e) {
System.out.println("No value at
index");
}
FINALLY
The finally block is invoked whenever there is a
try block, whether or not an exception was thrown.
values.add("Jan");
try {
System.out.printf("Value at index
3: %d\n",values.get(3));
}catch (IndexOutOfBoundsException e)
{
System.out.println("No value at
index");
}finally {
System.out.println("Cleanup
operation");
}</string>
ANNOTATIONS
ANNOTATIONS IN JAVA
Annotations are a form of metadata that provides
information about a program and is not part of it.
Annotations do not directly affect the operation of the
code they refer to.
ANNOTATION SYNTAX
The annotation consists of an @ character, which tells
the compiler that it is dealing with an annotation, and
a name, e.g.
@interface ComponentInject {
Class newClass();
String name();
}
USE
We can use the annotations when declaring, among
others classes, fields, methods:
@ComponentInject(clasz =
VideoSignatureService.class, name =
"videoSignature")
class VideoService {
}
BASICS OF REFLECTIONS
REFLECTION API
Reflection, whose classes are in the
java.lang.reflect package, allows you to access
each class's constructors, methods, and fields, as well
as their names, types, signatures, and so on. This
allows you to manipulate almost any class element.
REFLECTION API - EXAMPLE OF USE
Reflection can be used, for example, to:
implementation of code analysis tools
implementation of frameworks for the
implementation of dependency injection
implementation of data serialization /
deserialization mechanisms
Class<!--?--> carClass =
Class.forName("reflection.Car");
Method isPrototypeMethod =
carClass.getDeclaredMethod("isPrototype");
isPrototypeMethod.setAccessible(true);
System.out.println("Is Prototype
name: " + isPrototypeMethod.invoke(car));