How do you check security like your generic API?

You can use for example. JUnit to test the functionality of your library, but how do you check its type safety against generics and wildcards?

Only testing against codes that compile is a test of the "bon voyage"; should you also check your API for non-type usage and confirm that these codes DO NOT compile?

   // how do you write and verify these kinds of "tests"?

    List<Number> numbers = new ArrayList<Number>();
    List<Object> objects = new ArrayList<Object>();

    objects.addAll(numbers); // expect: this compiles

    numbers.addAll(objects); // expect: this does not compile

So, how do you confirm that your generic API raises the correct errors at compile time? Do you just create a set of non-compiling code to test your library and view the compilation error as a successful test and vice versa? (Of course, you must confirm that the errors are related to generics).

Is there a framework to facilitate such testing?

+5
source share
7 answers

Since this is not testing in the traditional sense (that is, you cannot "run" the test), and I do not think that such a tool exists, here is what I can offer:

  • Do a regular unit test
  • Create a code in it - both the correct code and the wrong code
  • Use the Java compiler API to try to compile it and check the result

You can make an easy-to-use wrapper for this functionality and contribute to everyone who has your requirements.

+6
source

, Java, , , ( api).

, , , , , , ?!

+5

, . . , , , . , ( ). , , ! !

, , . , , , . , dev, , .

+3

" API?" , :

  • @SuppressWarnings
  • , ( )

, " " API, . Java 5 , , (ClassCastException), ( , ). pre-Java 5, , " ", , . , , Java .

, ( ), " ". , , ArrayList<T>, addAll , . , Collection<T>, Collection<? extends T>, , . , , -, : , addAll, Collection<?> Collection<? super T>.

, , - , , - . , Java , Java , Class<T>, , clazz.newInstance(), .

+1

, Collections.checkedList() unit test. , ClassCassException. @Simon G.

List<String> stringList = new ArrayList<String>();
List<Number> numberList = Collections.checkedList(new ArrayList<Number>(), Number.class);
stringList.add("a string");
List list = stringList;
numberList.addAll(list);
System.out.println("Number list is " + numberList);
0

, , . .

, :

  • (, , JRT).
  • (FindBugs/CheckStyle)
  • ++ , concepts ( , ).

"", , " , add, , ". , .

0

, ++ , .

Using Eclipse, I get pretty quick from time to time when something in Java doesn't compile and the error messages are pretty straight forward. For example, if you expect the type to have a specific method call, then your compiler will tell you what you need to know. Same thing with type mismatches.

Good luck building time compilation in java: P

0
source

All Articles