Created
March 31, 2017 01:28
-
-
Save gom/82704126f296af3da5931703b70c25e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
version '1.0-SNAPSHOT' | |
apply plugin: 'java' | |
apply plugin: 'application' | |
mainClassName = 'sandbox.SandboxMain' | |
sourceCompatibility = 1.8 | |
repositories { | |
mavenCentral() | |
} | |
dependencies { | |
compile "javax.validation:validation-api:1.1.0.Final" | |
compile "org.glassfish.web:el-impl:2.2" | |
compile "org.hibernate:hibernate-validator:5.4.1.Final" | |
compileOnly 'org.projectlombok:lombok:1.16.10' | |
testCompile group: 'junit', name: 'junit', version: '4.11' | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sandbox; | |
import java.util.Set; | |
import javax.validation.ConstraintViolation; | |
import javax.validation.Validation; | |
import javax.validation.Validator; | |
import javax.validation.ValidatorFactory; | |
import javax.validation.constraints.NotNull; | |
import lombok.NonNull; | |
public class SandboxMain { | |
public static void main(String[] args) throws Exception { | |
String foo = null; | |
try { | |
nonNull(foo); // => Null Pointer Exception | |
} catch (NullPointerException e) { | |
System.out.println("@NonNull: " + e.getMessage()); | |
} | |
notNullWrong(foo); | |
notNull(); | |
} | |
private static void nonNull(@NonNull String foo) { | |
System.out.println(foo); | |
} | |
private static void notNullWrong(@NotNull String foo) { | |
// 何も起こらない | |
System.out.println("Wrong @NotNull: " + foo); | |
} | |
private static void notNull() { | |
Foo foo = new Foo(null); | |
validate(foo); | |
} | |
private static <T> void validate(T obj) { | |
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); | |
Validator validator = validatorFactory.getValidator(); | |
Set<ConstraintViolation<T>> violations = validator.validate(obj); | |
for (ConstraintViolation<T> violation : violations) { | |
System.out.println(violation.getMessage()); | |
} | |
} | |
static class Foo { | |
@NotNull | |
private String foo = null; | |
Foo(String foo) { | |
this.foo = foo; | |
} | |
private Foo() { } | |
public void foo() { | |
System.out.println(foo); | |
} | |
} | |
} | |
/* => outputs | |
@NonNull: foo | |
Wrong @NotNull: null | |
[DATE] org.hibernate.validator.internal.util.Version <clinit> | |
INFO: HV000001: Hibernate Validator 5.4.1.Final | |
may not be null | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment