-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCheck.java
More file actions
62 lines (56 loc) · 2.16 KB
/
Copy pathCheck.java
File metadata and controls
62 lines (56 loc) · 2.16 KB
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
58
59
60
61
62
/*
* Copyright 2015 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.diffplug.jscriptbox;
import java.util.Objects;
import java.util.Optional;
/** Cheap (and performant) knock-off of Guava's Preconditions class. */
public final class Check {
private Check() {}
/** If test is false, throws an exception with a message where {@code %0} is replaced with {@code Objects.toString(o0)}. */
public static void that(boolean test, String errorMsg, Object o0) {
if (!test) {
errorMsg = errorMsg.replace("%0", Objects.toString(o0));
throw new IllegalArgumentException(errorMsg);
}
}
/** If test is false, throws an exception with a message where {@code %0}, {@code %1} is replaced with {@code Objects.toString(o0)}, {@code Objects.toString(o1)}. */
public static void that(boolean test, String errorMsg, Object o0, Object o1) {
if (!test) {
errorMsg = errorMsg
.replace("%0", Objects.toString(o0))
.replace("%1", Objects.toString(o1));
throw new IllegalArgumentException(errorMsg);
}
}
@SuppressWarnings("unchecked")
public static <T> T cast(Object o, Class<T> clazz) {
if (o == null) {
throw new IllegalArgumentException("Expected object of type '" + clazz + "', was 'null'");
} else {
Check.that(clazz.isAssignableFrom(o.getClass()), "Expected object of type '%0', was '%1'", clazz, o.getClass());
return (T) o;
}
}
@SuppressWarnings("unchecked")
public static <T> Optional<T> castOpt(Object o, Class<T> clazz) {
if (o == null) {
return Optional.empty();
} else {
Check.that(clazz.isAssignableFrom(o.getClass()), "Expected object of type '%0', was '%1'", clazz, o.getClass());
return Optional.of((T) o);
}
}
}