Skip to content

Commit cc2e08c

Browse files
committed
Day 3 Final, with annotation examples
1 parent dca6b37 commit cc2e08c

3 files changed

Lines changed: 73 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package annotations;
2+
3+
import java.lang.reflect.Constructor;
4+
import java.lang.reflect.Method;
5+
6+
public class Framework {
7+
public static void main(String[] args) throws Throwable {
8+
System.setSecurityManager(new SecurityManager());
9+
String classname = "annotations.SomeTests";
10+
Class<?> theClass = Class.forName(classname);
11+
12+
Constructor<?> cons = theClass.getConstructor();
13+
Object obj = cons.newInstance();
14+
15+
System.out.println("Type of created object is " + obj.getClass().getName());
16+
// Method[] methods = theClass.getMethods();
17+
Method[] methods = theClass.getDeclaredMethods();
18+
19+
for (Method m : methods) {
20+
System.out.println("> " + m);
21+
RunMe annotation = m.getAnnotation(RunMe.class);
22+
if (annotation != null) {
23+
System.out.println("RunMe Annotation found!!! name is " + annotation.name());
24+
m.setAccessible(true);
25+
m.invoke(obj);
26+
}
27+
}
28+
}
29+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package annotations;
2+
3+
//public @ interface RunMe {
4+
5+
import java.lang.annotation.ElementType;
6+
import java.lang.annotation.Retention;
7+
import java.lang.annotation.RetentionPolicy;
8+
import java.lang.annotation.Target;
9+
10+
//@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
11+
@Target(ElementType.METHOD)
12+
@Retention(RetentionPolicy.RUNTIME)
13+
public @interface RunMe {
14+
// types of elements are strictly limited
15+
// compiler must be able to "fill in" the value at compilation (i.e. from sourcecode)
16+
// primitives, String, Class, other annotations (but circularity is prohibited)
17+
// and arrays of the above (no multi-dimensional arrays!)
18+
String name() default "Unknown";
19+
int value();
20+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package annotations;
2+
3+
//@RunMe
4+
public class SomeTests {
5+
// @RunMe
6+
String data = "hello";
7+
8+
@RunMe(name="Fred", value=3)
9+
public void tryThis() {
10+
System.out.println("running test tryThis");
11+
}
12+
13+
// @RunMe(name="Jim")
14+
// @RunMe()
15+
// @RunMe(value=3)
16+
@RunMe(3)
17+
private void tryThat() {
18+
System.out.println("Running test tryThat");
19+
}
20+
21+
public void dontTryTheOther() {
22+
System.out.println("oops, not supposed to run this");
23+
}
24+
}

0 commit comments

Comments
 (0)