Annotations and Reflection
Class Literal
A class literal gives a program a Class object without creating an instance.
class literal
The `.class` syntax asks Java for metadata about a type.
Class object
A Class object describes a type and exposes names, package data, methods, fields, and constructors.
Class Literal
ClassLiteral.java
Replay: real traced execution (multi-file project)
public class ClassLiteral {
public static void main(String[] args) {
int choice = 1;
Class<?> type;
if (choice == 1) {
type = String.class;
} else if (choice == 2) {
type = Integer.class;
} else {
type = Boolean.class;
}
System.out.println("simple=" + type.getSimpleName());
System.out.println("package=" + type.getPackageName());
}
}
public class ClassLiteral {
public static void main(String[] args) {
int choice = 2;
Class<?> type;
if (choice == 1) {
type = String.class;
} else if (choice == 2) {
type = Integer.class;
} else {
type = Boolean.class;
}
System.out.println("simple=" + type.getSimpleName());
System.out.println("package=" + type.getPackageName());
}
}
public class ClassLiteral {
public static void main(String[] args) {
int choice = 3;
Class<?> type;
if (choice == 1) {
type = String.class;
} else if (choice == 2) {
type = Integer.class;
} else {
type = Boolean.class;
}
System.out.println("simple=" + type.getSimpleName());
System.out.println("package=" + type.getPackageName());
}
}
choice ← 1
1public class ClassLiteral {2 public static void main(String[] args) {3 int choice→ 1 = 1; //@choice=2, 34 Class<?> type;type ← class java.lang.String
6if (choice1 == 1) {7 type→ class java.lang.String = String.class;8} else if (choice == 2) {System.out.println("simple=" + type.getSimpleName());
14 System.out.println("simple=" + type.getSimpleName());15 System.out.println("package=" + type.getPackageName());16}outputsimple=String package=java.lang
choice ← 2
1public class ClassLiteral {2 public static void main(String[] args) {3 int choice→ 2 = 2;4 Class<?> type;type ← class java.lang.Integer
7 type = String.class;8} else if (choice2 == 2) {9 type→ class java.lang.Integer = Integer.class;10} else {System.out.println("simple=" + type.getSimpleName());
14 System.out.println("simple=" + type.getSimpleName());15 System.out.println("package=" + type.getPackageName());16}outputsimple=Integer package=java.lang
choice ← 3
1public class ClassLiteral {2 public static void main(String[] args) {3 int choice→ 3 = 3;4 Class<?> type;type ← class java.lang.Boolean
9 type = Integer.class;10} else {11 type→ class java.lang.Boolean = Boolean.class;12}System.out.println("simple=" + type.getSimpleName());
14 System.out.println("simple=" + type.getSimpleName());15 System.out.println("package=" + type.getPackageName());16}outputsimple=Boolean package=java.lang