-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJavaCompilerCollectionExploitTests.java
57 lines (42 loc) · 1.53 KB
/
JavaCompilerCollectionExploitTests.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.github.vitmonk.javanotes.compiler;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* Trick java compiler =).
*/
public class JavaCompilerCollectionExploitTests {
@Test
public void testJavaCompilerForUnsafeOperations() {
List<Apple> appleList = new ArrayList<>();
appleList.add(new Apple());
System.out.println(appleList);
List<?> unknownList = (List<?>) appleList;
List<Object> objectList = (List<Object>) unknownList;
objectList.add(new Orange());
// now the apple list has also an orange
System.out.println(objectList);
// compiler error: use of unchecked or unsafe operation
// List<Apple> appleList2 = (List<Apple>) objectList;
// compiled successfully
List<Apple> appleList2 = castBack(objectList);
System.out.println(appleList2);
for (int index = 0; index < appleList2.size(); index++) {
System.out.print("Try to access " + (index + 1) + " apple.");
try {
Apple apple = appleList2.get(index);
System.out.println(" And it was: " + apple);
} catch (ClassCastException e) {
System.out.println(" But it was not an apple! Got " + appleList2.get(index) + " !");
System.out.println(e);
}
}
}
private List<Apple> castBack(List<?> objectList) {
return (List<Apple>) objectList;
}
private class Apple {
}
private class Orange {
}
}