code
stringlengths 11
173k
| docstring
stringlengths 2
593k
| func_name
stringlengths 2
189
| language
stringclasses 1
value | repo
stringclasses 844
values | path
stringlengths 11
294
| url
stringlengths 60
339
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
public static String bpsToSize(long bps) {
if (bps == 0) {
return "0";
}
double k = 1000;
String[] sizes = new String[]{"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
double i = Math.floor(Math.log(bps) / Math.log(k));
return NumberUtil.round(bps / Math.pow(k, i), 3) + " " + sizes[(int) i];
} |
将带宽大小转换为可读单位
@param bps
字节数
@return 带宽大小可读单位
| SizeToStrUtils::bpsToSize | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/SizeToStrUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/SizeToStrUtils.java | MIT |
public static Enum<?> convertStrToEnum(Class<?> clazz, Object value) {
if (!ClassUtil.isEnum(clazz)) {
return null;
}
Field[] fields = ReflectUtil.getFields(clazz);
for (Field field : fields) {
boolean jsonValuePresent = field.isAnnotationPresent(JsonValue.class);
boolean enumValuePresent = field.isAnnotationPresent(EnumValue.class);
if (jsonValuePresent || enumValuePresent) {
Object[] enumConstants = clazz.getEnumConstants();
for (Object enumObj : enumConstants) {
if (ObjectUtil.equal(value, ReflectUtil.getFieldValue(enumObj, field))) {
return (Enum<?>) enumObj;
}
}
}
}
return null;
} |
根据枚举 class 和值获取对应的枚举对象
@param clazz
枚举类 Class
@param value
枚举值
@return 枚举对象
| EnumConvertUtils::convertStrToEnum | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/EnumConvertUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/EnumConvertUtils.java | MIT |
public static boolean testCompatibilityGlobPattern(String pattern, String test) {
// 如果规则表达式最开始没有 /, 则兼容在最前方加上 /.
if (!StrUtil.startWith(pattern, ZFileConstant.PATH_SEPARATOR)) {
pattern = ZFileConstant.PATH_SEPARATOR + pattern;
}
// 兼容性处理.
test = StringUtils.concat(test, ZFileConstant.PATH_SEPARATOR);
if (StrUtil.endWith(pattern, "/**")) {
test += "xxx";
}
return testGlobPattern(pattern, test);
} |
兼容模式的 glob 表达式匹配.
默认的 glob 表达式是不支持以下情况的:<br>
<ul>
<li>pattern: /a/**</li>
<li>test1: /a</li>
<li>test2: /a/</li>
<ul>
<p>test1 和 test 2 均无法匹配这种情况, 此方法兼容了这种情况, 即对 test 内容后拼接 "/xx", 使其可以匹配上 pattern.
<p><strong>注意:</strong>但此方法对包含文件名的情况无效, 仅支持 test 为 路径的情况.
@param pattern
glob 规则表达式
@param test
匹配内容
@return 是否匹配.
| PatternMatcherUtils::testCompatibilityGlobPattern | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/PatternMatcherUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/PatternMatcherUtils.java | MIT |
private static boolean testGlobPattern(String pattern, String test) {
// 从缓存取出 PathMatcher, 防止重复初始化
PathMatcher pathMatcher = PATH_MATCHER_MAP.getOrDefault(pattern, FileSystems.getDefault().getPathMatcher("glob:" + pattern));
PATH_MATCHER_MAP.put(pattern, pathMatcher);
return pathMatcher.matches(Paths.get(test)) || StrUtil.equals(pattern, test);
} |
测试密码规则表达式和文件路径是否匹配
@param pattern
glob 规则表达式
@param test
测试字符串
| PatternMatcherUtils::testGlobPattern | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/PatternMatcherUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/PatternMatcherUtils.java | MIT |
public static HttpServletRequest getRequest(){
return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
} |
获取 HttpServletRequest
@return HttpServletRequest
| RequestHolder::getRequest | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/RequestHolder.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/RequestHolder.java | MIT |
public static HttpServletResponse getResponse(){
return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
} |
获取 HttpServletResponse
@return HttpServletResponse
| RequestHolder::getResponse | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/RequestHolder.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/RequestHolder.java | MIT |
public static void writeFile(Function<String, InputStream> function, String path){
try (InputStream inputStream = function.apply(path)) {
HttpServletResponse response = RequestHolder.getResponse();
String fileName = FileUtil.getName(path);
response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + StringUtils.encodeAllIgnoreSlashes(fileName));
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
OutputStream outputStream = response.getOutputStream();
IoUtil.copy(inputStream, outputStream);
response.flushBuffer();
} catch (IOException e) {
throw new RuntimeException(e);
}
} |
向 response 写入文件流.
@param function
文件输入流获取函数
@param path
文件路径
| RequestHolder::writeFile | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/RequestHolder.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/RequestHolder.java | MIT |
public static String trimSlashes(String path) {
path = trimStartSlashes(path);
path = trimEndSlashes(path);
return path;
} |
移除 URL 中的前后的所有 '/'
@param path
路径
@return 如 path = '/folder1/file1/', 返回 'folder1/file1'
如 path = '///folder1/file1//', 返回 'folder1/file1'
| StringUtils::trimSlashes | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | MIT |
public static String trimStartSlashes(String path) {
if (StrUtil.isEmpty(path)) {
return path;
}
while (path.startsWith(DELIMITER_STR)) {
path = path.substring(1);
}
return path;
} |
移除 URL 中的第一个 '/'
@param path
路径
@return 如 path = '/folder1/file1', 返回 'folder1/file1'
如 path = '/folder1/file1', 返回 'folder1/file1'
| StringUtils::trimStartSlashes | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | MIT |
public static String trimEndSlashes(String path) {
if (StrUtil.isEmpty(path)) {
return path;
}
while (path.endsWith(DELIMITER_STR)) {
path = path.substring(0, path.length() - 1);
}
return path;
} |
移除 URL 中的最后一个 '/'
@param path
路径
@return 如 path = '/folder1/file1/', 返回 '/folder1/file1'
如 path = '/folder1/file1///', 返回 '/folder1/file1'
| StringUtils::trimEndSlashes | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | MIT |
public static String removeDuplicateSlashes(String path) {
if (StrUtil.isEmpty(path)) {
return path;
}
StringBuilder sb = new StringBuilder();
// 是否包含 http 或 https 协议信息
boolean containProtocol = StrUtil.containsAnyIgnoreCase(path, HTTP_PROTOCOL, HTTPS_PROTOCOL);
if (containProtocol) {
path = trimStartSlashes(path);
}
// 是否包含 http 协议信息
boolean startWithHttpProtocol = StrUtil.startWithIgnoreCase(path, HTTP_PROTOCOL);
// 是否包含 https 协议信息
boolean startWithHttpsProtocol = StrUtil.startWithIgnoreCase(path, HTTPS_PROTOCOL);
if (startWithHttpProtocol) {
sb.append(HTTP_PROTOCOL);
} else if (startWithHttpsProtocol) {
sb.append(HTTPS_PROTOCOL);
}
for (int i = sb.length(); i < path.length() - 1; i++) {
char current = path.charAt(i);
char next = path.charAt(i + 1);
if (!(current == DELIMITER && next == DELIMITER)) {
sb.append(current);
}
}
sb.append(path.charAt(path.length() - 1));
return sb.toString();
} |
去除路径中所有重复的 '/'
@param path
路径
@return 如 path = '/folder1//file1/', 返回 '/folder1/file1/'
如 path = '/folder1////file1///', 返回 '/folder1/file1/'
| StringUtils::removeDuplicateSlashes | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | MIT |
public static String removeDuplicateSlashesAndTrimStart(String path) {
path = removeDuplicateSlashes(path);
path = trimStartSlashes(path);
return path;
} |
去除路径中所有重复的 '/', 并且去除开头的 '/'
@param path
路径
@return 如 path = '/folder1//file1/', 返回 'folder1/file1/'
如 path = '///folder1////file1///', 返回 'folder1/file1/'
| StringUtils::removeDuplicateSlashesAndTrimStart | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | MIT |
public static String removeDuplicateSlashesAndTrimEnd(String path) {
path = removeDuplicateSlashes(path);
path = trimEndSlashes(path);
return path;
} |
去除路径中所有重复的 '/', 并且去除结尾的 '/'
@param path
路径
@return 如 path = '/folder1//file1/', 返回 '/folder1/file1'
如 path = '///folder1////file1///', 返回 '/folder1/file1'
| StringUtils::removeDuplicateSlashesAndTrimEnd | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | MIT |
public static String concatTrimStartSlashes(String... strs) {
return trimStartSlashes(concat(strs));
} |
拼接 URL,并去除重复的分隔符 '/',并去除开头的 '/', 但不会影响 http:// 和 https:// 这种头部.
@param strs
拼接的字符数组
@return 拼接结果
| StringUtils::concatTrimStartSlashes | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | MIT |
public static String concatTrimEndSlashes(String... strs) {
return trimEndSlashes(concat(strs));
} |
拼接 URL,并去除重复的分隔符 '/',并去除结尾的 '/', 但不会影响 http:// 和 https:// 这种头部.
@param strs
拼接的字符数组
@return 拼接结果
| StringUtils::concatTrimEndSlashes | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | MIT |
public static String concatTrimSlashes(String... strs) {
return trimSlashes(concat(strs));
} |
拼接 URL,并去除重复的分隔符 '/',并去除开头和结尾的 '/', 但不会影响 http:// 和 https:// 这种头部.
@param strs
拼接的字符数组
@return 拼接结果
| StringUtils::concatTrimSlashes | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | MIT |
public static String concat(String... strs) {
StringBuilder sb = new StringBuilder(DELIMITER_STR);
for (int i = 0; i < strs.length; i++) {
String str = strs[i];
if (StrUtil.isEmpty(str)) {
continue;
}
sb.append(str);
if (i != strs.length - 1) {
sb.append(DELIMITER);
}
}
return removeDuplicateSlashes(sb.toString());
} |
拼接 URL,并去除重复的分隔符 '/',但不会影响 http:// 和 https:// 这种头部.
@param strs
拼接的字符数组
@return 拼接结果
| StringUtils::concat | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | MIT |
public static String concat(boolean encodeAllIgnoreSlashes, String... strs) {
StringBuilder sb = new StringBuilder(DELIMITER_STR);
for (int i = 0; i < strs.length; i++) {
String str = strs[i];
if (StrUtil.isEmpty(str)) {
continue;
}
sb.append(str);
if (i != strs.length - 1) {
sb.append(DELIMITER);
}
}
if (encodeAllIgnoreSlashes) {
return encodeAllIgnoreSlashes(removeDuplicateSlashes(sb.toString()));
} else {
return removeDuplicateSlashes(sb.toString());
}
} |
拼接 URL,并去除重复的分隔符 '/',但不会影响 http:// 和 https:// 这种头部.
@param encodeAllIgnoreSlashes
是否 encode 编码 (忽略 /)
@param strs
拼接的字符数组
@return 拼接结果
| StringUtils::concat | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | MIT |
public static String generatorPathLink(String storageKey, String fullPath) {
SystemConfigService systemConfigService = SpringUtil.getBean(SystemConfigService.class);
SystemConfigDTO systemConfig = systemConfigService.getSystemConfig();
String domain = systemConfig.getDomain();
String directLinkPrefix = systemConfig.getDirectLinkPrefix();
return concat(domain, directLinkPrefix, storageKey, encodeAllIgnoreSlashes(fullPath));
} |
拼接文件直链生成 URL
@param storageKey
存储源 ID
@param fullPath
文件全路径
@return 生成结果
| StringUtils::generatorPathLink | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/util/StringUtils.java | MIT |
public HttpLoggingInterceptor setLevel(Level level) {
if (level == null) throw new NullPointerException("level == null. Use Level.NONE instead.");
this.level = level;
return this;
} |
Logs request and response lines and their respective headers and bodies (if present).
<p>Example:
<pre>{@code
--> POST /greeting http/1.1
Host: example.com
Content-Type: plain/text
Content-Length: 3
Hi?
--> END POST
<-- 200 OK (22ms)
Content-Type: plain/text
Content-Length: 6
Hello!
<-- END HTTP
}</pre>
BODY
}
public interface Logger {
void log(String message);
/** A {@link Logger} defaults output appropriate for the current platform.
Logger DEFAULT = message -> Platform.get().log(message, INFO, null);
Logger DEBUG = log::debug;
Logger TRACE = log::trace;
}
public HttpLoggingInterceptor() {
this(Logger.DEFAULT);
}
public HttpLoggingInterceptor(Logger logger) {
this.logger = logger;
}
private final Logger logger;
private volatile Set<String> headersToRedact = Collections.emptySet();
public void redactHeader(String name) {
Set<String> newHeadersToRedact = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
newHeadersToRedact.addAll(headersToRedact);
newHeadersToRedact.add(name);
headersToRedact = newHeadersToRedact;
}
private volatile Level level = Level.NONE;
/** Change the level at which this interceptor logs. | HttpLoggingInterceptor::setLevel | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/httpclient/logging/HttpLoggingInterceptor.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/httpclient/logging/HttpLoggingInterceptor.java | MIT |
static boolean isPlaintext(Buffer buffer) {
try {
Buffer prefix = new Buffer();
long byteCount = buffer.size() < 64 ? buffer.size() : 64;
buffer.copyTo(prefix, 0, byteCount);
for (int i = 0; i < 16; i++) {
if (prefix.exhausted()) {
break;
}
int codePoint = prefix.readUtf8CodePoint();
if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
return false;
}
}
return true;
} catch (EOFException e) {
return false; // Truncated UTF-8 sequence.
}
} |
Returns true if the body in question probably contains human readable text. Uses a small sample
of code points to detect unicode control characters commonly used in binary file signatures.
| HttpLoggingInterceptor::isPlaintext | java | zfile-dev/zfile | src/main/java/im/zhaojun/zfile/core/httpclient/logging/HttpLoggingInterceptor.java | https://github.com/zfile-dev/zfile/blob/master/src/main/java/im/zhaojun/zfile/core/httpclient/logging/HttpLoggingInterceptor.java | MIT |
default Review createReview(Review body){return null;} |
Create a new review for a product.
@param body review to be created.
@return just created review.
| createReview | java | mohamed-taman/Springy-Store-Microservices | store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/review/ReviewService.java | https://github.com/mohamed-taman/Springy-Store-Microservices/blob/master/store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/review/ReviewService.java | MIT |
default void deleteReviews(int productId){} |
Delete all product reviews.
@param productId to delete its reviews.
| deleteReviews | java | mohamed-taman/Springy-Store-Microservices | store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/review/ReviewService.java | https://github.com/mohamed-taman/Springy-Store-Microservices/blob/master/store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/review/ReviewService.java | MIT |
default Product createProduct(Product body) {
return null;
} |
Add product to the repository.
@param body product to save.
@since v0.1
| createProduct | java | mohamed-taman/Springy-Store-Microservices | store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/product/ProductService.java | https://github.com/mohamed-taman/Springy-Store-Microservices/blob/master/store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/product/ProductService.java | MIT |
default void deleteProduct(int id) {} |
Delete the product from repository.
@implNote This method should be idempotent and always return 200 OK status.
@param id to be deleted.
@since v0.1
| deleteProduct | java | mohamed-taman/Springy-Store-Microservices | store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/product/ProductService.java | https://github.com/mohamed-taman/Springy-Store-Microservices/blob/master/store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/product/ProductService.java | MIT |
default Recommendation createRecommendation(Recommendation body) {
return null;
} |
Create a new recommendation for a product.
@param body the recommendation to add.
@return currently created recommendation.
@since v0.1
| createRecommendation | java | mohamed-taman/Springy-Store-Microservices | store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/recommendation/RecommendationService.java | https://github.com/mohamed-taman/Springy-Store-Microservices/blob/master/store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/recommendation/RecommendationService.java | MIT |
default void deleteRecommendations(int productId) {} |
Delete all product recommendations.
@param productId to delete recommendations for.
@since v0.1
| deleteRecommendations | java | mohamed-taman/Springy-Store-Microservices | store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/recommendation/RecommendationService.java | https://github.com/mohamed-taman/Springy-Store-Microservices/blob/master/store-common/store-api/src/main/java/com/siriusxi/ms/store/api/core/recommendation/RecommendationService.java | MIT |
public String packageName() {
return packageName;
} |
Returns the package name, like {@code "java.util"} for {@code Map.Entry}. Returns the empty
string for the default package.
| ClassName::packageName | java | square/javapoet | src/main/java/com/squareup/javapoet/ClassName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java | Apache-2.0 |
public ClassName enclosingClassName() {
return enclosingClassName;
} |
Returns the enclosing class, like {@link Map} for {@code Map.Entry}. Returns null if this class
is not nested in another class.
| ClassName::enclosingClassName | java | square/javapoet | src/main/java/com/squareup/javapoet/ClassName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java | Apache-2.0 |
public ClassName topLevelClassName() {
return enclosingClassName != null ? enclosingClassName.topLevelClassName() : this;
} |
Returns the top class in this nesting group. Equivalent to chained calls to {@link
#enclosingClassName()} until the result's enclosing class is null.
| ClassName::topLevelClassName | java | square/javapoet | src/main/java/com/squareup/javapoet/ClassName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java | Apache-2.0 |
public String reflectionName() {
return enclosingClassName != null
? (enclosingClassName.reflectionName() + '$' + simpleName)
: (packageName.isEmpty() ? simpleName : packageName + '.' + simpleName);
} |
Returns the top class in this nesting group. Equivalent to chained calls to {@link
#enclosingClassName()} until the result's enclosing class is null.
public ClassName topLevelClassName() {
return enclosingClassName != null ? enclosingClassName.topLevelClassName() : this;
}
/** Return the binary name of a class. | ClassName::reflectionName | java | square/javapoet | src/main/java/com/squareup/javapoet/ClassName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java | Apache-2.0 |
public ClassName peerClass(String name) {
return new ClassName(packageName, enclosingClassName, name);
} |
Returns a class that shares the same enclosing package or class. If this class is enclosed by
another class, this is equivalent to {@code enclosingClassName().nestedClass(name)}. Otherwise
it is equivalent to {@code get(packageName(), name)}.
| ClassName::peerClass | java | square/javapoet | src/main/java/com/squareup/javapoet/ClassName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java | Apache-2.0 |
public ClassName nestedClass(String name) {
return new ClassName(packageName, this, name);
} |
Returns a new {@link ClassName} instance for the specified {@code name} as nested inside this
class.
| ClassName::nestedClass | java | square/javapoet | src/main/java/com/squareup/javapoet/ClassName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java | Apache-2.0 |
public String simpleName() {
return simpleName;
} |
Returns a new {@link ClassName} instance for the specified {@code name} as nested inside this
class.
public ClassName nestedClass(String name) {
return new ClassName(packageName, this, name);
}
/** Returns the simple name of this class, like {@code "Entry"} for {@link Map.Entry}. | ClassName::simpleName | java | square/javapoet | src/main/java/com/squareup/javapoet/ClassName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java | Apache-2.0 |
public String canonicalName() {
return canonicalName;
} |
Returns the full class name of this class.
Like {@code "java.util.Map.Entry"} for {@link Map.Entry}.
* | ClassName::canonicalName | java | square/javapoet | src/main/java/com/squareup/javapoet/ClassName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ClassName.java | Apache-2.0 |
public boolean isPrimitive() {
return keyword != null && this != VOID;
} |
Returns true if this is a primitive type like {@code int}. Returns false for all other types
types including boxed primitives and {@code void}.
| TypeName::isPrimitive | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeName.java | Apache-2.0 |
public boolean isBoxedPrimitive() {
TypeName thisWithoutAnnotations = withoutAnnotations();
return thisWithoutAnnotations.equals(BOXED_BOOLEAN)
|| thisWithoutAnnotations.equals(BOXED_BYTE)
|| thisWithoutAnnotations.equals(BOXED_SHORT)
|| thisWithoutAnnotations.equals(BOXED_INT)
|| thisWithoutAnnotations.equals(BOXED_LONG)
|| thisWithoutAnnotations.equals(BOXED_CHAR)
|| thisWithoutAnnotations.equals(BOXED_FLOAT)
|| thisWithoutAnnotations.equals(BOXED_DOUBLE);
} |
Returns true if this is a boxed primitive type like {@code Integer}. Returns false for all
other types types including unboxed primitives and {@code java.lang.Void}.
| TypeName::isBoxedPrimitive | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeName.java | Apache-2.0 |
public TypeName box() {
if (keyword == null) return this; // Doesn't need boxing.
TypeName boxed = null;
if (keyword.equals(VOID.keyword)) boxed = BOXED_VOID;
else if (keyword.equals(BOOLEAN.keyword)) boxed = BOXED_BOOLEAN;
else if (keyword.equals(BYTE.keyword)) boxed = BOXED_BYTE;
else if (keyword.equals(SHORT.keyword)) boxed = BOXED_SHORT;
else if (keyword.equals(INT.keyword)) boxed = BOXED_INT;
else if (keyword.equals(LONG.keyword)) boxed = BOXED_LONG;
else if (keyword.equals(CHAR.keyword)) boxed = BOXED_CHAR;
else if (keyword.equals(FLOAT.keyword)) boxed = BOXED_FLOAT;
else if (keyword.equals(DOUBLE.keyword)) boxed = BOXED_DOUBLE;
else throw new AssertionError(keyword);
return annotations.isEmpty() ? boxed : boxed.annotated(annotations);
} |
Returns a boxed type if this is a primitive type (like {@code Integer} for {@code int}) or
{@code void}. Returns this type if boxing doesn't apply.
| TypeName::box | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeName.java | Apache-2.0 |
public TypeName unbox() {
if (keyword != null) return this; // Already unboxed.
TypeName thisWithoutAnnotations = withoutAnnotations();
TypeName unboxed = null;
if (thisWithoutAnnotations.equals(BOXED_VOID)) unboxed = VOID;
else if (thisWithoutAnnotations.equals(BOXED_BOOLEAN)) unboxed = BOOLEAN;
else if (thisWithoutAnnotations.equals(BOXED_BYTE)) unboxed = BYTE;
else if (thisWithoutAnnotations.equals(BOXED_SHORT)) unboxed = SHORT;
else if (thisWithoutAnnotations.equals(BOXED_INT)) unboxed = INT;
else if (thisWithoutAnnotations.equals(BOXED_LONG)) unboxed = LONG;
else if (thisWithoutAnnotations.equals(BOXED_CHAR)) unboxed = CHAR;
else if (thisWithoutAnnotations.equals(BOXED_FLOAT)) unboxed = FLOAT;
else if (thisWithoutAnnotations.equals(BOXED_DOUBLE)) unboxed = DOUBLE;
else throw new UnsupportedOperationException("cannot unbox " + this);
return annotations.isEmpty() ? unboxed : unboxed.annotated(annotations);
} |
Returns an unboxed type if this is a boxed primitive type (like {@code int} for {@code
Integer}) or {@code Void}. Returns this type if it is already unboxed.
@throws UnsupportedOperationException if this type isn't eligible for unboxing.
| TypeName::unbox | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeName.java | Apache-2.0 |
public static TypeName get(TypeMirror mirror) {
return get(mirror, new LinkedHashMap<>());
} |
Returns an unboxed type if this is a boxed primitive type (like {@code int} for {@code
Integer}) or {@code Void}. Returns this type if it is already unboxed.
@throws UnsupportedOperationException if this type isn't eligible for unboxing.
public TypeName unbox() {
if (keyword != null) return this; // Already unboxed.
TypeName thisWithoutAnnotations = withoutAnnotations();
TypeName unboxed = null;
if (thisWithoutAnnotations.equals(BOXED_VOID)) unboxed = VOID;
else if (thisWithoutAnnotations.equals(BOXED_BOOLEAN)) unboxed = BOOLEAN;
else if (thisWithoutAnnotations.equals(BOXED_BYTE)) unboxed = BYTE;
else if (thisWithoutAnnotations.equals(BOXED_SHORT)) unboxed = SHORT;
else if (thisWithoutAnnotations.equals(BOXED_INT)) unboxed = INT;
else if (thisWithoutAnnotations.equals(BOXED_LONG)) unboxed = LONG;
else if (thisWithoutAnnotations.equals(BOXED_CHAR)) unboxed = CHAR;
else if (thisWithoutAnnotations.equals(BOXED_FLOAT)) unboxed = FLOAT;
else if (thisWithoutAnnotations.equals(BOXED_DOUBLE)) unboxed = DOUBLE;
else throw new UnsupportedOperationException("cannot unbox " + this);
return annotations.isEmpty() ? unboxed : unboxed.annotated(annotations);
}
@Override public final boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (getClass() != o.getClass()) return false;
return toString().equals(o.toString());
}
@Override public final int hashCode() {
return toString().hashCode();
}
@Override public final String toString() {
String result = cachedString;
if (result == null) {
try {
StringBuilder resultBuilder = new StringBuilder();
CodeWriter codeWriter = new CodeWriter(resultBuilder);
emit(codeWriter);
result = resultBuilder.toString();
cachedString = result;
} catch (IOException e) {
throw new AssertionError();
}
}
return result;
}
CodeWriter emit(CodeWriter out) throws IOException {
if (keyword == null) throw new AssertionError();
if (isAnnotated()) {
out.emit("");
emitAnnotations(out);
}
return out.emitAndIndent(keyword);
}
CodeWriter emitAnnotations(CodeWriter out) throws IOException {
for (AnnotationSpec annotation : annotations) {
annotation.emit(out, true);
out.emit(" ");
}
return out;
}
/** Returns a type name equivalent to {@code mirror}. | TypeName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeName.java | Apache-2.0 |
public static TypeName get(Type type) {
return get(type, new LinkedHashMap<>());
} |
Returns an unboxed type if this is a boxed primitive type (like {@code int} for {@code
Integer}) or {@code Void}. Returns this type if it is already unboxed.
@throws UnsupportedOperationException if this type isn't eligible for unboxing.
public TypeName unbox() {
if (keyword != null) return this; // Already unboxed.
TypeName thisWithoutAnnotations = withoutAnnotations();
TypeName unboxed = null;
if (thisWithoutAnnotations.equals(BOXED_VOID)) unboxed = VOID;
else if (thisWithoutAnnotations.equals(BOXED_BOOLEAN)) unboxed = BOOLEAN;
else if (thisWithoutAnnotations.equals(BOXED_BYTE)) unboxed = BYTE;
else if (thisWithoutAnnotations.equals(BOXED_SHORT)) unboxed = SHORT;
else if (thisWithoutAnnotations.equals(BOXED_INT)) unboxed = INT;
else if (thisWithoutAnnotations.equals(BOXED_LONG)) unboxed = LONG;
else if (thisWithoutAnnotations.equals(BOXED_CHAR)) unboxed = CHAR;
else if (thisWithoutAnnotations.equals(BOXED_FLOAT)) unboxed = FLOAT;
else if (thisWithoutAnnotations.equals(BOXED_DOUBLE)) unboxed = DOUBLE;
else throw new UnsupportedOperationException("cannot unbox " + this);
return annotations.isEmpty() ? unboxed : unboxed.annotated(annotations);
}
@Override public final boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (getClass() != o.getClass()) return false;
return toString().equals(o.toString());
}
@Override public final int hashCode() {
return toString().hashCode();
}
@Override public final String toString() {
String result = cachedString;
if (result == null) {
try {
StringBuilder resultBuilder = new StringBuilder();
CodeWriter codeWriter = new CodeWriter(resultBuilder);
emit(codeWriter);
result = resultBuilder.toString();
cachedString = result;
} catch (IOException e) {
throw new AssertionError();
}
}
return result;
}
CodeWriter emit(CodeWriter out) throws IOException {
if (keyword == null) throw new AssertionError();
if (isAnnotated()) {
out.emit("");
emitAnnotations(out);
}
return out.emitAndIndent(keyword);
}
CodeWriter emitAnnotations(CodeWriter out) throws IOException {
for (AnnotationSpec annotation : annotations) {
annotation.emit(out, true);
out.emit(" ");
}
return out;
}
/** Returns a type name equivalent to {@code mirror}.
public static TypeName get(TypeMirror mirror) {
return get(mirror, new LinkedHashMap<>());
}
static TypeName get(TypeMirror mirror,
final Map<TypeParameterElement, TypeVariableName> typeVariables) {
return mirror.accept(new SimpleTypeVisitor8<TypeName, Void>() {
@Override public TypeName visitPrimitive(PrimitiveType t, Void p) {
switch (t.getKind()) {
case BOOLEAN:
return TypeName.BOOLEAN;
case BYTE:
return TypeName.BYTE;
case SHORT:
return TypeName.SHORT;
case INT:
return TypeName.INT;
case LONG:
return TypeName.LONG;
case CHAR:
return TypeName.CHAR;
case FLOAT:
return TypeName.FLOAT;
case DOUBLE:
return TypeName.DOUBLE;
default:
throw new AssertionError();
}
}
@Override public TypeName visitDeclared(DeclaredType t, Void p) {
ClassName rawType = ClassName.get((TypeElement) t.asElement());
TypeMirror enclosingType = t.getEnclosingType();
TypeName enclosing =
(enclosingType.getKind() != TypeKind.NONE)
&& !t.asElement().getModifiers().contains(Modifier.STATIC)
? enclosingType.accept(this, null)
: null;
if (t.getTypeArguments().isEmpty() && !(enclosing instanceof ParameterizedTypeName)) {
return rawType;
}
List<TypeName> typeArgumentNames = new ArrayList<>();
for (TypeMirror mirror : t.getTypeArguments()) {
typeArgumentNames.add(get(mirror, typeVariables));
}
return enclosing instanceof ParameterizedTypeName
? ((ParameterizedTypeName) enclosing).nestedClass(
rawType.simpleName(), typeArgumentNames)
: new ParameterizedTypeName(null, rawType, typeArgumentNames);
}
@Override public TypeName visitError(ErrorType t, Void p) {
return visitDeclared(t, p);
}
@Override public ArrayTypeName visitArray(ArrayType t, Void p) {
return ArrayTypeName.get(t, typeVariables);
}
@Override public TypeName visitTypeVariable(javax.lang.model.type.TypeVariable t, Void p) {
return TypeVariableName.get(t, typeVariables);
}
@Override public TypeName visitWildcard(javax.lang.model.type.WildcardType t, Void p) {
return WildcardTypeName.get(t, typeVariables);
}
@Override public TypeName visitNoType(NoType t, Void p) {
if (t.getKind() == TypeKind.VOID) return TypeName.VOID;
return super.visitUnknown(t, p);
}
@Override protected TypeName defaultAction(TypeMirror e, Void p) {
throw new IllegalArgumentException("Unexpected type mirror: " + e);
}
}, null);
}
/** Returns a type name equivalent to {@code type}. | TypeName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeName.java | Apache-2.0 |
private TypeSpec(TypeSpec type) {
assert type.anonymousTypeArguments == null;
this.kind = type.kind;
this.name = type.name;
this.anonymousTypeArguments = null;
this.javadoc = type.javadoc;
this.annotations = Collections.emptyList();
this.modifiers = Collections.emptySet();
this.typeVariables = Collections.emptyList();
this.superclass = null;
this.superinterfaces = Collections.emptyList();
this.enumConstants = Collections.emptyMap();
this.fieldSpecs = Collections.emptyList();
this.staticBlock = type.staticBlock;
this.initializerBlock = type.initializerBlock;
this.methodSpecs = Collections.emptyList();
this.typeSpecs = Collections.emptyList();
this.originatingElements = Collections.emptyList();
this.nestedTypesSimpleNames = Collections.emptySet();
this.alwaysQualifiedNames = Collections.emptySet();
} |
Creates a dummy type spec for type-resolution only (in CodeWriter)
while emitting the type declaration but before entering the type body.
| TypeSpec::TypeSpec | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeSpec.java | Apache-2.0 |
public Builder avoidClashesWithNestedClasses(TypeElement typeElement) {
checkArgument(typeElement != null, "typeElement == null");
for (TypeElement nestedType : ElementFilter.typesIn(typeElement.getEnclosedElements())) {
alwaysQualify(nestedType.getSimpleName().toString());
}
TypeMirror superclass = typeElement.getSuperclass();
if (!(superclass instanceof NoType) && superclass instanceof DeclaredType) {
TypeElement superclassElement = (TypeElement) ((DeclaredType) superclass).asElement();
avoidClashesWithNestedClasses(superclassElement);
}
for (TypeMirror superinterface : typeElement.getInterfaces()) {
if (superinterface instanceof DeclaredType) {
TypeElement superinterfaceElement
= (TypeElement) ((DeclaredType) superinterface).asElement();
avoidClashesWithNestedClasses(superinterfaceElement);
}
}
return this;
} |
Call this to always fully qualify any types that would conflict with possibly nested types of
this {@code typeElement}. For example - if the following type was passed in as the
typeElement:
<pre><code>
class Foo {
class NestedTypeA {
}
class NestedTypeB {
}
}
</code></pre>
<p>
Then this would add {@code "NestedTypeA"} and {@code "NestedTypeB"} as names that should
always be qualified via {@link #alwaysQualify(String...)}. This way they would avoid
possible import conflicts when this JavaFile is written.
@param typeElement the {@link TypeElement} with nested types to avoid clashes with.
@return this builder instance.
| Builder::avoidClashesWithNestedClasses | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeSpec.java | Apache-2.0 |
public void emitModifiers(Set<Modifier> modifiers, Set<Modifier> implicitModifiers)
throws IOException {
if (modifiers.isEmpty()) return;
for (Modifier modifier : EnumSet.copyOf(modifiers)) {
if (implicitModifiers.contains(modifier)) continue;
emitAndIndent(modifier.name().toLowerCase(Locale.US));
emitAndIndent(" ");
}
} |
Emits {@code modifiers} in the standard order. Modifiers in {@code implicitModifiers} will not
be emitted.
| CodeWriter::emitModifiers | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeWriter.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeWriter.java | Apache-2.0 |
public void emitTypeVariables(List<TypeVariableName> typeVariables) throws IOException {
if (typeVariables.isEmpty()) return;
typeVariables.forEach(typeVariable -> currentTypeVariables.add(typeVariable.name));
emit("<");
boolean firstTypeVariable = true;
for (TypeVariableName typeVariable : typeVariables) {
if (!firstTypeVariable) emit(", ");
emitAnnotations(typeVariable.annotations, true);
emit("$L", typeVariable.name);
boolean firstBound = true;
for (TypeName bound : typeVariable.bounds) {
emit(firstBound ? " extends $T" : " & $T", bound);
firstBound = false;
}
firstTypeVariable = false;
}
emit(">");
} |
Emit type variables with their bounds. This should only be used when declaring type variables;
everywhere else bounds are omitted.
| CodeWriter::emitTypeVariables | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeWriter.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeWriter.java | Apache-2.0 |
String lookupName(ClassName className) {
// If the top level simple name is masked by a current type variable, use the canonical name.
String topLevelSimpleName = className.topLevelClassName().simpleName();
if (currentTypeVariables.contains(topLevelSimpleName)) {
return className.canonicalName;
}
// Find the shortest suffix of className that resolves to className. This uses both local type
// names (so `Entry` in `Map` refers to `Map.Entry`). Also uses imports.
boolean nameResolved = false;
for (ClassName c = className; c != null; c = c.enclosingClassName()) {
ClassName resolved = resolve(c.simpleName());
nameResolved = resolved != null;
if (resolved != null && Objects.equals(resolved.canonicalName, c.canonicalName)) {
int suffixOffset = c.simpleNames().size() - 1;
return join(".", className.simpleNames().subList(
suffixOffset, className.simpleNames().size()));
}
}
// If the name resolved but wasn't a match, we're stuck with the fully qualified name.
if (nameResolved) {
return className.canonicalName;
}
// If the class is in the same package, we're done.
if (Objects.equals(packageName, className.packageName())) {
referencedNames.add(topLevelSimpleName);
return join(".", className.simpleNames());
}
// We'll have to use the fully-qualified name. Mark the type as importable for a future pass.
if (!javadoc) {
importableType(className);
}
return className.canonicalName;
} |
Returns the best name to identify {@code className} with in the current context. This uses the
available imports and the current scope to find the shortest name available. It does not honor
names visible due to inheritance.
| CodeWriter::lookupName | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeWriter.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeWriter.java | Apache-2.0 |
private ClassName stackClassName(int stackDepth, String simpleName) {
ClassName className = ClassName.get(packageName, typeSpecStack.get(0).name);
for (int i = 1; i <= stackDepth; i++) {
className = className.nestedClass(typeSpecStack.get(i).name);
}
return className.nestedClass(simpleName);
} |
Returns the class referenced by {@code simpleName}, using the current nesting context and
imports.
// TODO(jwilson): also honor superclass members when resolving names.
private ClassName resolve(String simpleName) {
// Match a child of the current (potentially nested) class.
for (int i = typeSpecStack.size() - 1; i >= 0; i--) {
TypeSpec typeSpec = typeSpecStack.get(i);
if (typeSpec.nestedTypesSimpleNames.contains(simpleName)) {
return stackClassName(i, simpleName);
}
}
// Match the top-level class.
if (typeSpecStack.size() > 0 && Objects.equals(typeSpecStack.get(0).name, simpleName)) {
return ClassName.get(packageName, simpleName);
}
// Match an imported type.
ClassName importedType = importedTypes.get(simpleName);
if (importedType != null) return importedType;
// No match.
return null;
}
/** Returns the class named {@code simpleName} when nested in the class at {@code stackDepth}. | CodeWriter::stackClassName | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeWriter.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeWriter.java | Apache-2.0 |
CodeWriter emitAndIndent(String s) throws IOException {
boolean first = true;
for (String line : LINE_BREAKING_PATTERN.split(s, -1)) {
// Emit a newline character. Make sure blank lines in Javadoc & comments look good.
if (!first) {
if ((javadoc || comment) && trailingNewline) {
emitIndentation();
out.append(javadoc ? " *" : "//");
}
out.append("\n");
trailingNewline = true;
if (statementLine != -1) {
if (statementLine == 0) {
indent(2); // Begin multiple-line statement. Increase the indentation level.
}
statementLine++;
}
}
first = false;
if (line.isEmpty()) continue; // Don't indent empty lines.
// Emit indentation and comment prefix if necessary.
if (trailingNewline) {
emitIndentation();
if (javadoc) {
out.append(" * ");
} else if (comment) {
out.append("// ");
}
}
out.append(line);
trailingNewline = false;
}
return this;
} |
Emits {@code s} with indentation as required. It's important that all code that writes to
{@link #out} does it through here, since we emit indentation lazily in order to avoid
unnecessary trailing whitespace.
| CodeWriter::emitAndIndent | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeWriter.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeWriter.java | Apache-2.0 |
Map<String, ClassName> suggestedImports() {
Map<String, ClassName> result = new LinkedHashMap<>(importableTypes);
result.keySet().removeAll(referencedNames);
return result;
} |
Returns the types that should have been imported for this code. If there were any simple name
collisions, that type's first use is imported.
| CodeWriter::suggestedImports | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeWriter.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeWriter.java | Apache-2.0 |
public String newName(String suggestion) {
return newName(suggestion, UUID.randomUUID().toString());
} |
Return a new name using {@code suggestion} that will not be a Java identifier or clash with
other names.
| NameAllocator::newName | java | square/javapoet | src/main/java/com/squareup/javapoet/NameAllocator.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/NameAllocator.java | Apache-2.0 |
public String newName(String suggestion, Object tag) {
checkNotNull(suggestion, "suggestion");
checkNotNull(tag, "tag");
suggestion = toJavaIdentifier(suggestion);
while (SourceVersion.isKeyword(suggestion) || !allocatedNames.add(suggestion)) {
suggestion = suggestion + "_";
}
String replaced = tagToName.put(tag, suggestion);
if (replaced != null) {
tagToName.put(tag, replaced); // Put things back as they were!
throw new IllegalArgumentException("tag " + tag + " cannot be used for both '" + replaced
+ "' and '" + suggestion + "'");
}
return suggestion;
} |
Return a new name using {@code suggestion} that will not be a Java identifier or clash with
other names. The returned value can be queried multiple times by passing {@code tag} to
{@link #get(Object)}.
| NameAllocator::newName | java | square/javapoet | src/main/java/com/squareup/javapoet/NameAllocator.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/NameAllocator.java | Apache-2.0 |
public String get(Object tag) {
String result = tagToName.get(tag);
if (result == null) {
throw new IllegalArgumentException("unknown tag: " + tag);
}
return result;
} |
Return a new name using {@code suggestion} that will not be a Java identifier or clash with
other names. The returned value can be queried multiple times by passing {@code tag} to
{@link #get(Object)}.
public String newName(String suggestion, Object tag) {
checkNotNull(suggestion, "suggestion");
checkNotNull(tag, "tag");
suggestion = toJavaIdentifier(suggestion);
while (SourceVersion.isKeyword(suggestion) || !allocatedNames.add(suggestion)) {
suggestion = suggestion + "_";
}
String replaced = tagToName.put(tag, suggestion);
if (replaced != null) {
tagToName.put(tag, replaced); // Put things back as they were!
throw new IllegalArgumentException("tag " + tag + " cannot be used for both '" + replaced
+ "' and '" + suggestion + "'");
}
return suggestion;
}
public static String toJavaIdentifier(String suggestion) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < suggestion.length(); ) {
int codePoint = suggestion.codePointAt(i);
if (i == 0
&& !Character.isJavaIdentifierStart(codePoint)
&& Character.isJavaIdentifierPart(codePoint)) {
result.append("_");
}
int validCodePoint = Character.isJavaIdentifierPart(codePoint) ? codePoint : '_';
result.appendCodePoint(validCodePoint);
i += Character.charCount(codePoint);
}
return result.toString();
}
/** Retrieve a name created with {@link #newName(String, Object)}. | NameAllocator::get | java | square/javapoet | src/main/java/com/squareup/javapoet/NameAllocator.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/NameAllocator.java | Apache-2.0 |
static String stringLiteralWithDoubleQuotes(String value, String indent) {
StringBuilder result = new StringBuilder(value.length() + 2);
result.append('"');
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
// trivial case: single quote must not be escaped
if (c == '\'') {
result.append("'");
continue;
}
// trivial case: double quotes must be escaped
if (c == '\"') {
result.append("\\\"");
continue;
}
// default case: just let character literal do its work
result.append(characterLiteralWithoutSingleQuotes(c));
// need to append indent after linefeed?
if (c == '\n' && i + 1 < value.length()) {
result.append("\"\n").append(indent).append(indent).append("+ \"");
}
}
result.append('"');
return result.toString();
} |
Like Guava, but worse and standalone. This makes it easier to mix JavaPoet with libraries that
bring their own version of Guava.
final class Util {
private Util() {
}
static <K, V> Map<K, List<V>> immutableMultimap(Map<K, List<V>> multimap) {
LinkedHashMap<K, List<V>> result = new LinkedHashMap<>();
for (Map.Entry<K, List<V>> entry : multimap.entrySet()) {
if (entry.getValue().isEmpty()) continue;
result.put(entry.getKey(), immutableList(entry.getValue()));
}
return Collections.unmodifiableMap(result);
}
static <K, V> Map<K, V> immutableMap(Map<K, V> map) {
return Collections.unmodifiableMap(new LinkedHashMap<>(map));
}
static void checkArgument(boolean condition, String format, Object... args) {
if (!condition) throw new IllegalArgumentException(String.format(format, args));
}
static <T> T checkNotNull(T reference, String format, Object... args) {
if (reference == null) throw new NullPointerException(String.format(format, args));
return reference;
}
static void checkState(boolean condition, String format, Object... args) {
if (!condition) throw new IllegalStateException(String.format(format, args));
}
static <T> List<T> immutableList(Collection<T> collection) {
return Collections.unmodifiableList(new ArrayList<>(collection));
}
static <T> Set<T> immutableSet(Collection<T> set) {
return Collections.unmodifiableSet(new LinkedHashSet<>(set));
}
static <T> Set<T> union(Set<T> a, Set<T> b) {
Set<T> result = new LinkedHashSet<>();
result.addAll(a);
result.addAll(b);
return result;
}
static void requireExactlyOneOf(Set<Modifier> modifiers, Modifier... mutuallyExclusive) {
int count = 0;
for (Modifier modifier : mutuallyExclusive) {
if (modifiers.contains(modifier)) count++;
}
checkArgument(count == 1, "modifiers %s must contain one of %s",
modifiers, Arrays.toString(mutuallyExclusive));
}
static String characterLiteralWithoutSingleQuotes(char c) {
// see https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6
switch (c) {
case '\b': return "\\b"; /* \u0008: backspace (BS)
case '\t': return "\\t"; /* \u0009: horizontal tab (HT)
case '\n': return "\\n"; /* \u000a: linefeed (LF)
case '\f': return "\\f"; /* \u000c: form feed (FF)
case '\r': return "\\r"; /* \u000d: carriage return (CR)
case '\"': return "\""; /* \u0022: double quote (")
case '\'': return "\\'"; /* \u0027: single quote (')
case '\\': return "\\\\"; /* \u005c: backslash (\)
default:
return isISOControl(c) ? String.format("\\u%04x", (int) c) : Character.toString(c);
}
}
/** Returns the string literal representing {@code value}, including wrapping double quotes. | Util::stringLiteralWithDoubleQuotes | java | square/javapoet | src/main/java/com/squareup/javapoet/Util.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/Util.java | Apache-2.0 |
public Builder beginControlFlow(String controlFlow, Object... args) {
code.beginControlFlow(controlFlow, args);
return this;
} |
@param controlFlow the control flow construct and its code, such as "if (foo == 5)".
Shouldn't contain braces or newline characters.
| Builder::beginControlFlow | java | square/javapoet | src/main/java/com/squareup/javapoet/MethodSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/MethodSpec.java | Apache-2.0 |
public Builder beginControlFlow(CodeBlock codeBlock) {
return beginControlFlow("$L", codeBlock);
} |
@param codeBlock the control flow construct and its code, such as "if (foo == 5)".
Shouldn't contain braces or newline characters.
| Builder::beginControlFlow | java | square/javapoet | src/main/java/com/squareup/javapoet/MethodSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/MethodSpec.java | Apache-2.0 |
public Builder nextControlFlow(String controlFlow, Object... args) {
code.nextControlFlow(controlFlow, args);
return this;
} |
@param controlFlow the control flow construct and its code, such as "else if (foo == 10)".
Shouldn't contain braces or newline characters.
| Builder::nextControlFlow | java | square/javapoet | src/main/java/com/squareup/javapoet/MethodSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/MethodSpec.java | Apache-2.0 |
public Builder nextControlFlow(CodeBlock codeBlock) {
return nextControlFlow("$L", codeBlock);
} |
@param codeBlock the control flow construct and its code, such as "else if (foo == 10)".
Shouldn't contain braces or newline characters.
| Builder::nextControlFlow | java | square/javapoet | src/main/java/com/squareup/javapoet/MethodSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/MethodSpec.java | Apache-2.0 |
public Builder endControlFlow(String controlFlow, Object... args) {
code.endControlFlow(controlFlow, args);
return this;
} |
@param controlFlow the optional control flow construct and its code, such as
"while(foo == 20)". Only used for "do/while" control flows.
| Builder::endControlFlow | java | square/javapoet | src/main/java/com/squareup/javapoet/MethodSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/MethodSpec.java | Apache-2.0 |
public Builder endControlFlow(CodeBlock codeBlock) {
return endControlFlow("$L", codeBlock);
} |
@param codeBlock the optional control flow construct and its code, such as
"while(foo == 20)". Only used for "do/while" control flows.
| Builder::endControlFlow | java | square/javapoet | src/main/java/com/squareup/javapoet/MethodSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/MethodSpec.java | Apache-2.0 |
public static CodeBlock join(Iterable<CodeBlock> codeBlocks, String separator) {
return StreamSupport.stream(codeBlocks.spliterator(), false).collect(joining(separator));
} |
Joins {@code codeBlocks} into a single {@link CodeBlock}, each separated by {@code separator}.
For example, joining {@code String s}, {@code Object o} and {@code int i} using {@code ", "}
would produce {@code String s, Object o, int i}.
| CodeBlock::join | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeBlock.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeBlock.java | Apache-2.0 |
public static Collector<CodeBlock, ?, CodeBlock> joining(String separator) {
return Collector.of(
() -> new CodeBlockJoiner(separator, builder()),
CodeBlockJoiner::add,
CodeBlockJoiner::merge,
CodeBlockJoiner::join);
} |
A {@link Collector} implementation that joins {@link CodeBlock} instances together into one
separated by {@code separator}. For example, joining {@code String s}, {@code Object o} and
{@code int i} using {@code ", "} would produce {@code String s, Object o, int i}.
| CodeBlock::joining | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeBlock.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeBlock.java | Apache-2.0 |
public static Collector<CodeBlock, ?, CodeBlock> joining(
String separator, String prefix, String suffix) {
Builder builder = builder().add("$N", prefix);
return Collector.of(
() -> new CodeBlockJoiner(separator, builder),
CodeBlockJoiner::add,
CodeBlockJoiner::merge,
joiner -> {
builder.add(CodeBlock.of("$N", suffix));
return joiner.join();
});
} |
A {@link Collector} implementation that joins {@link CodeBlock} instances together into one
separated by {@code separator}. For example, joining {@code String s}, {@code Object o} and
{@code int i} using {@code ", "} would produce {@code String s, Object o, int i}.
| CodeBlock::joining | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeBlock.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeBlock.java | Apache-2.0 |
public Builder addNamed(String format, Map<String, ?> arguments) {
int p = 0;
for (String argument : arguments.keySet()) {
checkArgument(LOWERCASE.matcher(argument).matches(),
"argument '%s' must start with a lowercase character", argument);
}
while (p < format.length()) {
int nextP = format.indexOf("$", p);
if (nextP == -1) {
formatParts.add(format.substring(p));
break;
}
if (p != nextP) {
formatParts.add(format.substring(p, nextP));
p = nextP;
}
Matcher matcher = null;
int colon = format.indexOf(':', p);
if (colon != -1) {
int endIndex = Math.min(colon + 2, format.length());
matcher = NAMED_ARGUMENT.matcher(format.substring(p, endIndex));
}
if (matcher != null && matcher.lookingAt()) {
String argumentName = matcher.group("argumentName");
checkArgument(arguments.containsKey(argumentName), "Missing named argument for $%s",
argumentName);
char formatChar = matcher.group("typeChar").charAt(0);
addArgument(format, formatChar, arguments.get(argumentName));
formatParts.add("$" + formatChar);
p += matcher.regionEnd();
} else {
checkArgument(p < format.length() - 1, "dangling $ at end");
checkArgument(isNoArgPlaceholder(format.charAt(p + 1)),
"unknown format $%s at %s in '%s'", format.charAt(p + 1), p + 1, format);
formatParts.add(format.substring(p, p + 2));
p += 2;
}
}
return this;
} |
Adds code using named arguments.
<p>Named arguments specify their name after the '$' followed by : and the corresponding type
character. Argument names consist of characters in {@code a-z, A-Z, 0-9, and _} and must
start with a lowercase character.
<p>For example, to refer to the type {@link java.lang.Integer} with the argument name {@code
clazz} use a format string containing {@code $clazz:T} and include the key {@code clazz} with
value {@code java.lang.Integer.class} in the argument map.
| Builder::addNamed | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeBlock.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeBlock.java | Apache-2.0 |
public Builder add(String format, Object... args) {
boolean hasRelative = false;
boolean hasIndexed = false;
int relativeParameterCount = 0;
int[] indexedParameterCount = new int[args.length];
for (int p = 0; p < format.length(); ) {
if (format.charAt(p) != '$') {
int nextP = format.indexOf('$', p + 1);
if (nextP == -1) nextP = format.length();
formatParts.add(format.substring(p, nextP));
p = nextP;
continue;
}
p++; // '$'.
// Consume zero or more digits, leaving 'c' as the first non-digit char after the '$'.
int indexStart = p;
char c;
do {
checkArgument(p < format.length(), "dangling format characters in '%s'", format);
c = format.charAt(p++);
} while (c >= '0' && c <= '9');
int indexEnd = p - 1;
// If 'c' doesn't take an argument, we're done.
if (isNoArgPlaceholder(c)) {
checkArgument(
indexStart == indexEnd, "$$, $>, $<, $[, $], $W, and $Z may not have an index");
formatParts.add("$" + c);
continue;
}
// Find either the indexed argument, or the relative argument. (0-based).
int index;
if (indexStart < indexEnd) {
index = Integer.parseInt(format.substring(indexStart, indexEnd)) - 1;
hasIndexed = true;
if (args.length > 0) {
indexedParameterCount[index % args.length]++; // modulo is needed, checked below anyway
}
} else {
index = relativeParameterCount;
hasRelative = true;
relativeParameterCount++;
}
checkArgument(index >= 0 && index < args.length,
"index %d for '%s' not in range (received %s arguments)",
index + 1, format.substring(indexStart - 1, indexEnd + 1), args.length);
checkArgument(!hasIndexed || !hasRelative, "cannot mix indexed and positional parameters");
addArgument(format, c, args[index]);
formatParts.add("$" + c);
}
if (hasRelative) {
checkArgument(relativeParameterCount >= args.length,
"unused arguments: expected %s, received %s", relativeParameterCount, args.length);
}
if (hasIndexed) {
List<String> unused = new ArrayList<>();
for (int i = 0; i < args.length; i++) {
if (indexedParameterCount[i] == 0) {
unused.add("$" + (i + 1));
}
}
String s = unused.size() == 1 ? "" : "s";
checkArgument(unused.isEmpty(), "unused argument%s: %s", s, String.join(", ", unused));
}
return this;
} |
Add code with positional or relative arguments.
<p>Relative arguments map 1:1 with the placeholders in the format string.
<p>Positional arguments use an index after the placeholder to identify which argument index
to use. For example, for a literal to reference the 3rd argument: "$3L" (1 based index)
<p>Mixing relative and positional arguments in a call to add is invalid and will result in an
error.
| Builder::add | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeBlock.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeBlock.java | Apache-2.0 |
public Builder beginControlFlow(String controlFlow, Object... args) {
add(controlFlow + " {\n", args);
indent();
return this;
} |
@param controlFlow the control flow construct and its code, such as "if (foo == 5)".
Shouldn't contain braces or newline characters.
| Builder::beginControlFlow | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeBlock.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeBlock.java | Apache-2.0 |
public Builder nextControlFlow(String controlFlow, Object... args) {
unindent();
add("} " + controlFlow + " {\n", args);
indent();
return this;
} |
@param controlFlow the control flow construct and its code, such as "else if (foo == 10)".
Shouldn't contain braces or newline characters.
| Builder::nextControlFlow | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeBlock.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeBlock.java | Apache-2.0 |
public Builder endControlFlow(String controlFlow, Object... args) {
unindent();
add("} " + controlFlow + ";\n", args);
return this;
} |
@param controlFlow the optional control flow construct and its code, such as
"while(foo == 20)". Only used for "do/while" control flows.
| Builder::endControlFlow | java | square/javapoet | src/main/java/com/squareup/javapoet/CodeBlock.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/CodeBlock.java | Apache-2.0 |
char lastChar() {
return out.lastChar;
} |
Null if we have no buffering; otherwise the type to pass to the next call to {@link #flush}.
private FlushType nextFlush;
LineWrapper(Appendable out, String indent, int columnLimit) {
checkNotNull(out, "out == null");
this.out = new RecordingAppendable(out);
this.indent = indent;
this.columnLimit = columnLimit;
}
/** @return the last emitted char or {@link Character#MIN_VALUE} if nothing emitted yet. | LineWrapper::lastChar | java | square/javapoet | src/main/java/com/squareup/javapoet/LineWrapper.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/LineWrapper.java | Apache-2.0 |
void append(String s) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (nextFlush != null) {
int nextNewline = s.indexOf('\n');
// If s doesn't cause the current line to cross the limit, buffer it and return. We'll decide
// whether or not we have to wrap it later.
if (nextNewline == -1 && column + s.length() <= columnLimit) {
buffer.append(s);
column += s.length();
return;
}
// Wrap if appending s would overflow the current line.
boolean wrap = nextNewline == -1 || column + nextNewline > columnLimit;
flush(wrap ? FlushType.WRAP : nextFlush);
}
out.append(s);
int lastNewline = s.lastIndexOf('\n');
column = lastNewline != -1
? s.length() - lastNewline - 1
: column + s.length();
} |
Null if we have no buffering; otherwise the type to pass to the next call to {@link #flush}.
private FlushType nextFlush;
LineWrapper(Appendable out, String indent, int columnLimit) {
checkNotNull(out, "out == null");
this.out = new RecordingAppendable(out);
this.indent = indent;
this.columnLimit = columnLimit;
}
/** @return the last emitted char or {@link Character#MIN_VALUE} if nothing emitted yet.
char lastChar() {
return out.lastChar;
}
/** Emit {@code s}. This may be buffered to permit line wraps to be inserted. | LineWrapper::append | java | square/javapoet | src/main/java/com/squareup/javapoet/LineWrapper.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/LineWrapper.java | Apache-2.0 |
void wrappingSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (this.nextFlush != null) flush(nextFlush);
column++; // Increment the column even though the space is deferred to next call to flush().
this.nextFlush = FlushType.SPACE;
this.indentLevel = indentLevel;
} |
Null if we have no buffering; otherwise the type to pass to the next call to {@link #flush}.
private FlushType nextFlush;
LineWrapper(Appendable out, String indent, int columnLimit) {
checkNotNull(out, "out == null");
this.out = new RecordingAppendable(out);
this.indent = indent;
this.columnLimit = columnLimit;
}
/** @return the last emitted char or {@link Character#MIN_VALUE} if nothing emitted yet.
char lastChar() {
return out.lastChar;
}
/** Emit {@code s}. This may be buffered to permit line wraps to be inserted.
void append(String s) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (nextFlush != null) {
int nextNewline = s.indexOf('\n');
// If s doesn't cause the current line to cross the limit, buffer it and return. We'll decide
// whether or not we have to wrap it later.
if (nextNewline == -1 && column + s.length() <= columnLimit) {
buffer.append(s);
column += s.length();
return;
}
// Wrap if appending s would overflow the current line.
boolean wrap = nextNewline == -1 || column + nextNewline > columnLimit;
flush(wrap ? FlushType.WRAP : nextFlush);
}
out.append(s);
int lastNewline = s.lastIndexOf('\n');
column = lastNewline != -1
? s.length() - lastNewline - 1
: column + s.length();
}
/** Emit either a space or a newline character. | LineWrapper::wrappingSpace | java | square/javapoet | src/main/java/com/squareup/javapoet/LineWrapper.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/LineWrapper.java | Apache-2.0 |
void zeroWidthSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (column == 0) return;
if (this.nextFlush != null) flush(nextFlush);
this.nextFlush = FlushType.EMPTY;
this.indentLevel = indentLevel;
} |
Null if we have no buffering; otherwise the type to pass to the next call to {@link #flush}.
private FlushType nextFlush;
LineWrapper(Appendable out, String indent, int columnLimit) {
checkNotNull(out, "out == null");
this.out = new RecordingAppendable(out);
this.indent = indent;
this.columnLimit = columnLimit;
}
/** @return the last emitted char or {@link Character#MIN_VALUE} if nothing emitted yet.
char lastChar() {
return out.lastChar;
}
/** Emit {@code s}. This may be buffered to permit line wraps to be inserted.
void append(String s) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (nextFlush != null) {
int nextNewline = s.indexOf('\n');
// If s doesn't cause the current line to cross the limit, buffer it and return. We'll decide
// whether or not we have to wrap it later.
if (nextNewline == -1 && column + s.length() <= columnLimit) {
buffer.append(s);
column += s.length();
return;
}
// Wrap if appending s would overflow the current line.
boolean wrap = nextNewline == -1 || column + nextNewline > columnLimit;
flush(wrap ? FlushType.WRAP : nextFlush);
}
out.append(s);
int lastNewline = s.lastIndexOf('\n');
column = lastNewline != -1
? s.length() - lastNewline - 1
: column + s.length();
}
/** Emit either a space or a newline character.
void wrappingSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (this.nextFlush != null) flush(nextFlush);
column++; // Increment the column even though the space is deferred to next call to flush().
this.nextFlush = FlushType.SPACE;
this.indentLevel = indentLevel;
}
/** Emit a newline character if the line will exceed it's limit, otherwise do nothing. | LineWrapper::zeroWidthSpace | java | square/javapoet | src/main/java/com/squareup/javapoet/LineWrapper.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/LineWrapper.java | Apache-2.0 |
void close() throws IOException {
if (nextFlush != null) flush(nextFlush);
closed = true;
} |
Null if we have no buffering; otherwise the type to pass to the next call to {@link #flush}.
private FlushType nextFlush;
LineWrapper(Appendable out, String indent, int columnLimit) {
checkNotNull(out, "out == null");
this.out = new RecordingAppendable(out);
this.indent = indent;
this.columnLimit = columnLimit;
}
/** @return the last emitted char or {@link Character#MIN_VALUE} if nothing emitted yet.
char lastChar() {
return out.lastChar;
}
/** Emit {@code s}. This may be buffered to permit line wraps to be inserted.
void append(String s) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (nextFlush != null) {
int nextNewline = s.indexOf('\n');
// If s doesn't cause the current line to cross the limit, buffer it and return. We'll decide
// whether or not we have to wrap it later.
if (nextNewline == -1 && column + s.length() <= columnLimit) {
buffer.append(s);
column += s.length();
return;
}
// Wrap if appending s would overflow the current line.
boolean wrap = nextNewline == -1 || column + nextNewline > columnLimit;
flush(wrap ? FlushType.WRAP : nextFlush);
}
out.append(s);
int lastNewline = s.lastIndexOf('\n');
column = lastNewline != -1
? s.length() - lastNewline - 1
: column + s.length();
}
/** Emit either a space or a newline character.
void wrappingSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (this.nextFlush != null) flush(nextFlush);
column++; // Increment the column even though the space is deferred to next call to flush().
this.nextFlush = FlushType.SPACE;
this.indentLevel = indentLevel;
}
/** Emit a newline character if the line will exceed it's limit, otherwise do nothing.
void zeroWidthSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (column == 0) return;
if (this.nextFlush != null) flush(nextFlush);
this.nextFlush = FlushType.EMPTY;
this.indentLevel = indentLevel;
}
/** Flush any outstanding text and forbid future writes to this line wrapper. | LineWrapper::close | java | square/javapoet | src/main/java/com/squareup/javapoet/LineWrapper.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/LineWrapper.java | Apache-2.0 |
private void flush(FlushType flushType) throws IOException {
switch (flushType) {
case WRAP:
out.append('\n');
for (int i = 0; i < indentLevel; i++) {
out.append(indent);
}
column = indentLevel * indent.length();
column += buffer.length();
break;
case SPACE:
out.append(' ');
break;
case EMPTY:
break;
default:
throw new IllegalArgumentException("Unknown FlushType: " + flushType);
}
out.append(buffer);
buffer.delete(0, buffer.length());
indentLevel = -1;
nextFlush = null;
} |
Null if we have no buffering; otherwise the type to pass to the next call to {@link #flush}.
private FlushType nextFlush;
LineWrapper(Appendable out, String indent, int columnLimit) {
checkNotNull(out, "out == null");
this.out = new RecordingAppendable(out);
this.indent = indent;
this.columnLimit = columnLimit;
}
/** @return the last emitted char or {@link Character#MIN_VALUE} if nothing emitted yet.
char lastChar() {
return out.lastChar;
}
/** Emit {@code s}. This may be buffered to permit line wraps to be inserted.
void append(String s) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (nextFlush != null) {
int nextNewline = s.indexOf('\n');
// If s doesn't cause the current line to cross the limit, buffer it and return. We'll decide
// whether or not we have to wrap it later.
if (nextNewline == -1 && column + s.length() <= columnLimit) {
buffer.append(s);
column += s.length();
return;
}
// Wrap if appending s would overflow the current line.
boolean wrap = nextNewline == -1 || column + nextNewline > columnLimit;
flush(wrap ? FlushType.WRAP : nextFlush);
}
out.append(s);
int lastNewline = s.lastIndexOf('\n');
column = lastNewline != -1
? s.length() - lastNewline - 1
: column + s.length();
}
/** Emit either a space or a newline character.
void wrappingSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (this.nextFlush != null) flush(nextFlush);
column++; // Increment the column even though the space is deferred to next call to flush().
this.nextFlush = FlushType.SPACE;
this.indentLevel = indentLevel;
}
/** Emit a newline character if the line will exceed it's limit, otherwise do nothing.
void zeroWidthSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (column == 0) return;
if (this.nextFlush != null) flush(nextFlush);
this.nextFlush = FlushType.EMPTY;
this.indentLevel = indentLevel;
}
/** Flush any outstanding text and forbid future writes to this line wrapper.
void close() throws IOException {
if (nextFlush != null) flush(nextFlush);
closed = true;
}
/** Write the space followed by any buffered text that follows it. | LineWrapper::flush | java | square/javapoet | src/main/java/com/squareup/javapoet/LineWrapper.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/LineWrapper.java | Apache-2.0 |
public void writeTo(Path directory) throws IOException {
writeToPath(directory);
} | /*
Copyright (C) 2015 Square, Inc.
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.squareup.javapoet;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.processing.Filer;
import javax.lang.model.element.Element;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.SimpleJavaFileObject;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
import static java.nio.charset.StandardCharsets.UTF_8;
/** A Java file containing a single top level class.
public final class JavaFile {
private static final Appendable NULL_APPENDABLE = new Appendable() {
@Override public Appendable append(CharSequence charSequence) {
return this;
}
@Override public Appendable append(CharSequence charSequence, int start, int end) {
return this;
}
@Override public Appendable append(char c) {
return this;
}
};
public final CodeBlock fileComment;
public final String packageName;
public final TypeSpec typeSpec;
public final boolean skipJavaLangImports;
private final Set<String> staticImports;
private final Set<String> alwaysQualify;
private final String indent;
private JavaFile(Builder builder) {
this.fileComment = builder.fileComment.build();
this.packageName = builder.packageName;
this.typeSpec = builder.typeSpec;
this.skipJavaLangImports = builder.skipJavaLangImports;
this.staticImports = Util.immutableSet(builder.staticImports);
this.indent = builder.indent;
Set<String> alwaysQualifiedNames = new LinkedHashSet<>();
fillAlwaysQualifiedNames(builder.typeSpec, alwaysQualifiedNames);
this.alwaysQualify = Util.immutableSet(alwaysQualifiedNames);
}
private void fillAlwaysQualifiedNames(TypeSpec spec, Set<String> alwaysQualifiedNames) {
alwaysQualifiedNames.addAll(spec.alwaysQualifiedNames);
for (TypeSpec nested : spec.typeSpecs) {
fillAlwaysQualifiedNames(nested, alwaysQualifiedNames);
}
}
public void writeTo(Appendable out) throws IOException {
// First pass: emit the entire class, just to collect the types we'll need to import.
CodeWriter importsCollector = new CodeWriter(
NULL_APPENDABLE,
indent,
staticImports,
alwaysQualify
);
emit(importsCollector);
Map<String, ClassName> suggestedImports = importsCollector.suggestedImports();
// Second pass: write the code, taking advantage of the imports.
CodeWriter codeWriter
= new CodeWriter(out, indent, suggestedImports, staticImports, alwaysQualify);
emit(codeWriter);
}
/** Writes this to {@code directory} as UTF-8 using the standard directory structure. | JavaFile::writeTo | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
public void writeTo(Path directory, Charset charset) throws IOException {
writeToPath(directory, charset);
} |
Writes this to {@code directory} with the provided {@code charset} using the standard directory
structure.
| JavaFile::writeTo | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
public Path writeToPath(Path directory) throws IOException {
return writeToPath(directory, UTF_8);
} |
Writes this to {@code directory} as UTF-8 using the standard directory structure.
Returns the {@link Path} instance to which source is actually written.
| JavaFile::writeToPath | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
public Path writeToPath(Path directory, Charset charset) throws IOException {
checkArgument(Files.notExists(directory) || Files.isDirectory(directory),
"path %s exists but is not a directory.", directory);
Path outputDirectory = directory;
if (!packageName.isEmpty()) {
for (String packageComponent : packageName.split("\\.")) {
outputDirectory = outputDirectory.resolve(packageComponent);
}
Files.createDirectories(outputDirectory);
}
Path outputPath = outputDirectory.resolve(typeSpec.name + ".java");
try (Writer writer = new OutputStreamWriter(Files.newOutputStream(outputPath), charset)) {
writeTo(writer);
}
return outputPath;
} |
Writes this to {@code directory} with the provided {@code charset} using the standard directory
structure.
Returns the {@link Path} instance to which source is actually written.
| JavaFile::writeToPath | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
public void writeTo(File directory) throws IOException {
writeTo(directory.toPath());
} |
Writes this to {@code directory} with the provided {@code charset} using the standard directory
structure.
Returns the {@link Path} instance to which source is actually written.
public Path writeToPath(Path directory, Charset charset) throws IOException {
checkArgument(Files.notExists(directory) || Files.isDirectory(directory),
"path %s exists but is not a directory.", directory);
Path outputDirectory = directory;
if (!packageName.isEmpty()) {
for (String packageComponent : packageName.split("\\.")) {
outputDirectory = outputDirectory.resolve(packageComponent);
}
Files.createDirectories(outputDirectory);
}
Path outputPath = outputDirectory.resolve(typeSpec.name + ".java");
try (Writer writer = new OutputStreamWriter(Files.newOutputStream(outputPath), charset)) {
writeTo(writer);
}
return outputPath;
}
/** Writes this to {@code directory} as UTF-8 using the standard directory structure. | JavaFile::writeTo | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
public File writeToFile(File directory) throws IOException {
final Path outputPath = writeToPath(directory.toPath());
return outputPath.toFile();
} |
Writes this to {@code directory} as UTF-8 using the standard directory structure.
Returns the {@link File} instance to which source is actually written.
| JavaFile::writeToFile | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
public void writeTo(Filer filer) throws IOException {
String fileName = packageName.isEmpty()
? typeSpec.name
: packageName + "." + typeSpec.name;
List<Element> originatingElements = typeSpec.originatingElements;
JavaFileObject filerSourceFile = filer.createSourceFile(fileName,
originatingElements.toArray(new Element[originatingElements.size()]));
try (Writer writer = filerSourceFile.openWriter()) {
writeTo(writer);
} catch (Exception e) {
try {
filerSourceFile.delete();
} catch (Exception ignored) {
}
throw e;
}
} |
Writes this to {@code directory} as UTF-8 using the standard directory structure.
Returns the {@link File} instance to which source is actually written.
public File writeToFile(File directory) throws IOException {
final Path outputPath = writeToPath(directory.toPath());
return outputPath.toFile();
}
/** Writes this to {@code filer}. | JavaFile::writeTo | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
public Builder skipJavaLangImports(boolean skipJavaLangImports) {
this.skipJavaLangImports = skipJavaLangImports;
return this;
} |
Call this to omit imports for classes in {@code java.lang}, such as {@code java.lang.String}.
<p>By default, JavaPoet explicitly imports types in {@code java.lang} to defend against
naming conflicts. Suppose an (ill-advised) class is named {@code com.example.String}. When
{@code java.lang} imports are skipped, generated code in {@code com.example} that references
{@code java.lang.String} will get {@code com.example.String} instead.
| Builder::skipJavaLangImports | java | square/javapoet | src/main/java/com/squareup/javapoet/JavaFile.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/JavaFile.java | Apache-2.0 |
Builder addMemberForValue(String memberName, Object value) {
checkNotNull(memberName, "memberName == null");
checkNotNull(value, "value == null, constant non-null value expected for %s", memberName);
checkArgument(SourceVersion.isName(memberName), "not a valid name: %s", memberName);
if (value instanceof Class<?>) {
return addMember(memberName, "$T.class", value);
}
if (value instanceof Enum) {
return addMember(memberName, "$T.$L", value.getClass(), ((Enum<?>) value).name());
}
if (value instanceof String) {
return addMember(memberName, "$S", value);
}
if (value instanceof Float) {
return addMember(memberName, "$Lf", value);
}
if (value instanceof Long) {
return addMember(memberName, "$LL", value);
}
if (value instanceof Character) {
return addMember(memberName, "'$L'", characterLiteralWithoutSingleQuotes((char) value));
}
return addMember(memberName, "$L", value);
} |
Delegates to {@link #addMember(String, String, Object...)}, with parameter {@code format}
depending on the given {@code value} object. Falls back to {@code "$L"} literal format if
the class of the given {@code value} object is not supported.
| Builder::addMemberForValue | java | square/javapoet | src/main/java/com/squareup/javapoet/AnnotationSpec.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/AnnotationSpec.java | Apache-2.0 |
public static TypeVariableName get(String name) {
return TypeVariableName.of(name, Collections.emptyList());
} | /*
Copyright (C) 2015 Square, Inc.
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.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
public final class TypeVariableName extends TypeName {
public final String name;
public final List<TypeName> bounds;
private TypeVariableName(String name, List<TypeName> bounds) {
this(name, bounds, new ArrayList<>());
}
private TypeVariableName(String name, List<TypeName> bounds, List<AnnotationSpec> annotations) {
super(annotations);
this.name = checkNotNull(name, "name == null");
this.bounds = bounds;
for (TypeName bound : this.bounds) {
checkArgument(!bound.isPrimitive() && bound != VOID, "invalid bound: %s", bound);
}
}
@Override public TypeVariableName annotated(List<AnnotationSpec> annotations) {
return new TypeVariableName(name, bounds, annotations);
}
@Override public TypeName withoutAnnotations() {
return new TypeVariableName(name, bounds);
}
public TypeVariableName withBounds(Type... bounds) {
return withBounds(TypeName.list(bounds));
}
public TypeVariableName withBounds(TypeName... bounds) {
return withBounds(Arrays.asList(bounds));
}
public TypeVariableName withBounds(List<? extends TypeName> bounds) {
ArrayList<TypeName> newBounds = new ArrayList<>();
newBounds.addAll(this.bounds);
newBounds.addAll(bounds);
return new TypeVariableName(name, newBounds, annotations);
}
private static TypeVariableName of(String name, List<TypeName> bounds) {
// Strip java.lang.Object from bounds if it is present.
List<TypeName> boundsNoObject = new ArrayList<>(bounds);
boundsNoObject.remove(OBJECT);
return new TypeVariableName(name, Collections.unmodifiableList(boundsNoObject));
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
emitAnnotations(out);
return out.emitAndIndent(name);
}
/** Returns type variable named {@code name} without bounds. | TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
public static TypeVariableName get(String name, TypeName... bounds) {
return TypeVariableName.of(name, Arrays.asList(bounds));
} | /*
Copyright (C) 2015 Square, Inc.
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.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
public final class TypeVariableName extends TypeName {
public final String name;
public final List<TypeName> bounds;
private TypeVariableName(String name, List<TypeName> bounds) {
this(name, bounds, new ArrayList<>());
}
private TypeVariableName(String name, List<TypeName> bounds, List<AnnotationSpec> annotations) {
super(annotations);
this.name = checkNotNull(name, "name == null");
this.bounds = bounds;
for (TypeName bound : this.bounds) {
checkArgument(!bound.isPrimitive() && bound != VOID, "invalid bound: %s", bound);
}
}
@Override public TypeVariableName annotated(List<AnnotationSpec> annotations) {
return new TypeVariableName(name, bounds, annotations);
}
@Override public TypeName withoutAnnotations() {
return new TypeVariableName(name, bounds);
}
public TypeVariableName withBounds(Type... bounds) {
return withBounds(TypeName.list(bounds));
}
public TypeVariableName withBounds(TypeName... bounds) {
return withBounds(Arrays.asList(bounds));
}
public TypeVariableName withBounds(List<? extends TypeName> bounds) {
ArrayList<TypeName> newBounds = new ArrayList<>();
newBounds.addAll(this.bounds);
newBounds.addAll(bounds);
return new TypeVariableName(name, newBounds, annotations);
}
private static TypeVariableName of(String name, List<TypeName> bounds) {
// Strip java.lang.Object from bounds if it is present.
List<TypeName> boundsNoObject = new ArrayList<>(bounds);
boundsNoObject.remove(OBJECT);
return new TypeVariableName(name, Collections.unmodifiableList(boundsNoObject));
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
emitAnnotations(out);
return out.emitAndIndent(name);
}
/** Returns type variable named {@code name} without bounds.
public static TypeVariableName get(String name) {
return TypeVariableName.of(name, Collections.emptyList());
}
/** Returns type variable named {@code name} with {@code bounds}. | TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
public static TypeVariableName get(String name, Type... bounds) {
return TypeVariableName.of(name, TypeName.list(bounds));
} | /*
Copyright (C) 2015 Square, Inc.
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.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
public final class TypeVariableName extends TypeName {
public final String name;
public final List<TypeName> bounds;
private TypeVariableName(String name, List<TypeName> bounds) {
this(name, bounds, new ArrayList<>());
}
private TypeVariableName(String name, List<TypeName> bounds, List<AnnotationSpec> annotations) {
super(annotations);
this.name = checkNotNull(name, "name == null");
this.bounds = bounds;
for (TypeName bound : this.bounds) {
checkArgument(!bound.isPrimitive() && bound != VOID, "invalid bound: %s", bound);
}
}
@Override public TypeVariableName annotated(List<AnnotationSpec> annotations) {
return new TypeVariableName(name, bounds, annotations);
}
@Override public TypeName withoutAnnotations() {
return new TypeVariableName(name, bounds);
}
public TypeVariableName withBounds(Type... bounds) {
return withBounds(TypeName.list(bounds));
}
public TypeVariableName withBounds(TypeName... bounds) {
return withBounds(Arrays.asList(bounds));
}
public TypeVariableName withBounds(List<? extends TypeName> bounds) {
ArrayList<TypeName> newBounds = new ArrayList<>();
newBounds.addAll(this.bounds);
newBounds.addAll(bounds);
return new TypeVariableName(name, newBounds, annotations);
}
private static TypeVariableName of(String name, List<TypeName> bounds) {
// Strip java.lang.Object from bounds if it is present.
List<TypeName> boundsNoObject = new ArrayList<>(bounds);
boundsNoObject.remove(OBJECT);
return new TypeVariableName(name, Collections.unmodifiableList(boundsNoObject));
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
emitAnnotations(out);
return out.emitAndIndent(name);
}
/** Returns type variable named {@code name} without bounds.
public static TypeVariableName get(String name) {
return TypeVariableName.of(name, Collections.emptyList());
}
/** Returns type variable named {@code name} with {@code bounds}.
public static TypeVariableName get(String name, TypeName... bounds) {
return TypeVariableName.of(name, Arrays.asList(bounds));
}
/** Returns type variable named {@code name} with {@code bounds}. | TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
public static TypeVariableName get(TypeVariable mirror) {
return get((TypeParameterElement) mirror.asElement());
} | /*
Copyright (C) 2015 Square, Inc.
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.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
public final class TypeVariableName extends TypeName {
public final String name;
public final List<TypeName> bounds;
private TypeVariableName(String name, List<TypeName> bounds) {
this(name, bounds, new ArrayList<>());
}
private TypeVariableName(String name, List<TypeName> bounds, List<AnnotationSpec> annotations) {
super(annotations);
this.name = checkNotNull(name, "name == null");
this.bounds = bounds;
for (TypeName bound : this.bounds) {
checkArgument(!bound.isPrimitive() && bound != VOID, "invalid bound: %s", bound);
}
}
@Override public TypeVariableName annotated(List<AnnotationSpec> annotations) {
return new TypeVariableName(name, bounds, annotations);
}
@Override public TypeName withoutAnnotations() {
return new TypeVariableName(name, bounds);
}
public TypeVariableName withBounds(Type... bounds) {
return withBounds(TypeName.list(bounds));
}
public TypeVariableName withBounds(TypeName... bounds) {
return withBounds(Arrays.asList(bounds));
}
public TypeVariableName withBounds(List<? extends TypeName> bounds) {
ArrayList<TypeName> newBounds = new ArrayList<>();
newBounds.addAll(this.bounds);
newBounds.addAll(bounds);
return new TypeVariableName(name, newBounds, annotations);
}
private static TypeVariableName of(String name, List<TypeName> bounds) {
// Strip java.lang.Object from bounds if it is present.
List<TypeName> boundsNoObject = new ArrayList<>(bounds);
boundsNoObject.remove(OBJECT);
return new TypeVariableName(name, Collections.unmodifiableList(boundsNoObject));
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
emitAnnotations(out);
return out.emitAndIndent(name);
}
/** Returns type variable named {@code name} without bounds.
public static TypeVariableName get(String name) {
return TypeVariableName.of(name, Collections.emptyList());
}
/** Returns type variable named {@code name} with {@code bounds}.
public static TypeVariableName get(String name, TypeName... bounds) {
return TypeVariableName.of(name, Arrays.asList(bounds));
}
/** Returns type variable named {@code name} with {@code bounds}.
public static TypeVariableName get(String name, Type... bounds) {
return TypeVariableName.of(name, TypeName.list(bounds));
}
/** Returns type variable equivalent to {@code mirror}. | TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
static TypeVariableName get(
TypeVariable mirror, Map<TypeParameterElement, TypeVariableName> typeVariables) {
TypeParameterElement element = (TypeParameterElement) mirror.asElement();
TypeVariableName typeVariableName = typeVariables.get(element);
if (typeVariableName == null) {
// Since the bounds field is public, we need to make it an unmodifiableList. But we control
// the List that that wraps, which means we can change it before returning.
List<TypeName> bounds = new ArrayList<>();
List<TypeName> visibleBounds = Collections.unmodifiableList(bounds);
typeVariableName = new TypeVariableName(element.getSimpleName().toString(), visibleBounds);
typeVariables.put(element, typeVariableName);
for (TypeMirror typeMirror : element.getBounds()) {
bounds.add(TypeName.get(typeMirror, typeVariables));
}
bounds.remove(OBJECT);
}
return typeVariableName;
} |
Make a TypeVariableName for the given TypeMirror. This form is used internally to avoid
infinite recursion in cases like {@code Enum<E extends Enum<E>>}. When we encounter such a
thing, we will make a TypeVariableName without bounds and add that to the {@code typeVariables}
map before looking up the bounds. Then if we encounter this TypeVariable again while
constructing the bounds, we can just return it from the map. And, the code that put the entry
in {@code variables} will make sure that the bounds are filled in before returning.
| TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
public static TypeVariableName get(TypeParameterElement element) {
String name = element.getSimpleName().toString();
List<? extends TypeMirror> boundsMirrors = element.getBounds();
List<TypeName> boundsTypeNames = new ArrayList<>();
for (TypeMirror typeMirror : boundsMirrors) {
boundsTypeNames.add(TypeName.get(typeMirror));
}
return TypeVariableName.of(name, boundsTypeNames);
} |
Make a TypeVariableName for the given TypeMirror. This form is used internally to avoid
infinite recursion in cases like {@code Enum<E extends Enum<E>>}. When we encounter such a
thing, we will make a TypeVariableName without bounds and add that to the {@code typeVariables}
map before looking up the bounds. Then if we encounter this TypeVariable again while
constructing the bounds, we can just return it from the map. And, the code that put the entry
in {@code variables} will make sure that the bounds are filled in before returning.
static TypeVariableName get(
TypeVariable mirror, Map<TypeParameterElement, TypeVariableName> typeVariables) {
TypeParameterElement element = (TypeParameterElement) mirror.asElement();
TypeVariableName typeVariableName = typeVariables.get(element);
if (typeVariableName == null) {
// Since the bounds field is public, we need to make it an unmodifiableList. But we control
// the List that that wraps, which means we can change it before returning.
List<TypeName> bounds = new ArrayList<>();
List<TypeName> visibleBounds = Collections.unmodifiableList(bounds);
typeVariableName = new TypeVariableName(element.getSimpleName().toString(), visibleBounds);
typeVariables.put(element, typeVariableName);
for (TypeMirror typeMirror : element.getBounds()) {
bounds.add(TypeName.get(typeMirror, typeVariables));
}
bounds.remove(OBJECT);
}
return typeVariableName;
}
/** Returns type variable equivalent to {@code element}. | TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
public static TypeVariableName get(java.lang.reflect.TypeVariable<?> type) {
return get(type, new LinkedHashMap<>());
} |
Make a TypeVariableName for the given TypeMirror. This form is used internally to avoid
infinite recursion in cases like {@code Enum<E extends Enum<E>>}. When we encounter such a
thing, we will make a TypeVariableName without bounds and add that to the {@code typeVariables}
map before looking up the bounds. Then if we encounter this TypeVariable again while
constructing the bounds, we can just return it from the map. And, the code that put the entry
in {@code variables} will make sure that the bounds are filled in before returning.
static TypeVariableName get(
TypeVariable mirror, Map<TypeParameterElement, TypeVariableName> typeVariables) {
TypeParameterElement element = (TypeParameterElement) mirror.asElement();
TypeVariableName typeVariableName = typeVariables.get(element);
if (typeVariableName == null) {
// Since the bounds field is public, we need to make it an unmodifiableList. But we control
// the List that that wraps, which means we can change it before returning.
List<TypeName> bounds = new ArrayList<>();
List<TypeName> visibleBounds = Collections.unmodifiableList(bounds);
typeVariableName = new TypeVariableName(element.getSimpleName().toString(), visibleBounds);
typeVariables.put(element, typeVariableName);
for (TypeMirror typeMirror : element.getBounds()) {
bounds.add(TypeName.get(typeMirror, typeVariables));
}
bounds.remove(OBJECT);
}
return typeVariableName;
}
/** Returns type variable equivalent to {@code element}.
public static TypeVariableName get(TypeParameterElement element) {
String name = element.getSimpleName().toString();
List<? extends TypeMirror> boundsMirrors = element.getBounds();
List<TypeName> boundsTypeNames = new ArrayList<>();
for (TypeMirror typeMirror : boundsMirrors) {
boundsTypeNames.add(TypeName.get(typeMirror));
}
return TypeVariableName.of(name, boundsTypeNames);
}
/** Returns type variable equivalent to {@code type}. | TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
static TypeVariableName get(java.lang.reflect.TypeVariable<?> type,
Map<Type, TypeVariableName> map) {
TypeVariableName result = map.get(type);
if (result == null) {
List<TypeName> bounds = new ArrayList<>();
List<TypeName> visibleBounds = Collections.unmodifiableList(bounds);
result = new TypeVariableName(type.getName(), visibleBounds);
map.put(type, result);
for (Type bound : type.getBounds()) {
bounds.add(TypeName.get(bound, map));
}
bounds.remove(OBJECT);
}
return result;
} |
Make a TypeVariableName for the given TypeMirror. This form is used internally to avoid
infinite recursion in cases like {@code Enum<E extends Enum<E>>}. When we encounter such a
thing, we will make a TypeVariableName without bounds and add that to the {@code typeVariables}
map before looking up the bounds. Then if we encounter this TypeVariable again while
constructing the bounds, we can just return it from the map. And, the code that put the entry
in {@code variables} will make sure that the bounds are filled in before returning.
static TypeVariableName get(
TypeVariable mirror, Map<TypeParameterElement, TypeVariableName> typeVariables) {
TypeParameterElement element = (TypeParameterElement) mirror.asElement();
TypeVariableName typeVariableName = typeVariables.get(element);
if (typeVariableName == null) {
// Since the bounds field is public, we need to make it an unmodifiableList. But we control
// the List that that wraps, which means we can change it before returning.
List<TypeName> bounds = new ArrayList<>();
List<TypeName> visibleBounds = Collections.unmodifiableList(bounds);
typeVariableName = new TypeVariableName(element.getSimpleName().toString(), visibleBounds);
typeVariables.put(element, typeVariableName);
for (TypeMirror typeMirror : element.getBounds()) {
bounds.add(TypeName.get(typeMirror, typeVariables));
}
bounds.remove(OBJECT);
}
return typeVariableName;
}
/** Returns type variable equivalent to {@code element}.
public static TypeVariableName get(TypeParameterElement element) {
String name = element.getSimpleName().toString();
List<? extends TypeMirror> boundsMirrors = element.getBounds();
List<TypeName> boundsTypeNames = new ArrayList<>();
for (TypeMirror typeMirror : boundsMirrors) {
boundsTypeNames.add(TypeName.get(typeMirror));
}
return TypeVariableName.of(name, boundsTypeNames);
}
/** Returns type variable equivalent to {@code type}.
public static TypeVariableName get(java.lang.reflect.TypeVariable<?> type) {
return get(type, new LinkedHashMap<>());
}
/** @see #get(java.lang.reflect.TypeVariable, Map) | TypeVariableName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/TypeVariableName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/TypeVariableName.java | Apache-2.0 |
public static ArrayTypeName of(TypeName componentType) {
return new ArrayTypeName(componentType);
} | /*
Copyright (C) 2015 Square, Inc.
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.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.ArrayType;
import static com.squareup.javapoet.Util.checkNotNull;
public final class ArrayTypeName extends TypeName {
public final TypeName componentType;
private ArrayTypeName(TypeName componentType) {
this(componentType, new ArrayList<>());
}
private ArrayTypeName(TypeName componentType, List<AnnotationSpec> annotations) {
super(annotations);
this.componentType = checkNotNull(componentType, "rawType == null");
}
@Override public ArrayTypeName annotated(List<AnnotationSpec> annotations) {
return new ArrayTypeName(componentType, concatAnnotations(annotations));
}
@Override public TypeName withoutAnnotations() {
return new ArrayTypeName(componentType);
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
return emit(out, false);
}
CodeWriter emit(CodeWriter out, boolean varargs) throws IOException {
emitLeafType(out);
return emitBrackets(out, varargs);
}
private CodeWriter emitLeafType(CodeWriter out) throws IOException {
if (TypeName.asArray(componentType) != null) {
return TypeName.asArray(componentType).emitLeafType(out);
}
return componentType.emit(out);
}
private CodeWriter emitBrackets(CodeWriter out, boolean varargs) throws IOException {
if (isAnnotated()) {
out.emit(" ");
emitAnnotations(out);
}
if (TypeName.asArray(componentType) == null) {
// Last bracket.
return out.emit(varargs ? "..." : "[]");
}
out.emit("[]");
return TypeName.asArray(componentType) .emitBrackets(out, varargs);
}
/** Returns an array type whose elements are all instances of {@code componentType}. | ArrayTypeName::of | java | square/javapoet | src/main/java/com/squareup/javapoet/ArrayTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ArrayTypeName.java | Apache-2.0 |
public static ArrayTypeName of(Type componentType) {
return of(TypeName.get(componentType));
} | /*
Copyright (C) 2015 Square, Inc.
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.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.ArrayType;
import static com.squareup.javapoet.Util.checkNotNull;
public final class ArrayTypeName extends TypeName {
public final TypeName componentType;
private ArrayTypeName(TypeName componentType) {
this(componentType, new ArrayList<>());
}
private ArrayTypeName(TypeName componentType, List<AnnotationSpec> annotations) {
super(annotations);
this.componentType = checkNotNull(componentType, "rawType == null");
}
@Override public ArrayTypeName annotated(List<AnnotationSpec> annotations) {
return new ArrayTypeName(componentType, concatAnnotations(annotations));
}
@Override public TypeName withoutAnnotations() {
return new ArrayTypeName(componentType);
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
return emit(out, false);
}
CodeWriter emit(CodeWriter out, boolean varargs) throws IOException {
emitLeafType(out);
return emitBrackets(out, varargs);
}
private CodeWriter emitLeafType(CodeWriter out) throws IOException {
if (TypeName.asArray(componentType) != null) {
return TypeName.asArray(componentType).emitLeafType(out);
}
return componentType.emit(out);
}
private CodeWriter emitBrackets(CodeWriter out, boolean varargs) throws IOException {
if (isAnnotated()) {
out.emit(" ");
emitAnnotations(out);
}
if (TypeName.asArray(componentType) == null) {
// Last bracket.
return out.emit(varargs ? "..." : "[]");
}
out.emit("[]");
return TypeName.asArray(componentType) .emitBrackets(out, varargs);
}
/** Returns an array type whose elements are all instances of {@code componentType}.
public static ArrayTypeName of(TypeName componentType) {
return new ArrayTypeName(componentType);
}
/** Returns an array type whose elements are all instances of {@code componentType}. | ArrayTypeName::of | java | square/javapoet | src/main/java/com/squareup/javapoet/ArrayTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ArrayTypeName.java | Apache-2.0 |
public static ArrayTypeName get(ArrayType mirror) {
return get(mirror, new LinkedHashMap<>());
} | /*
Copyright (C) 2015 Square, Inc.
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.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.ArrayType;
import static com.squareup.javapoet.Util.checkNotNull;
public final class ArrayTypeName extends TypeName {
public final TypeName componentType;
private ArrayTypeName(TypeName componentType) {
this(componentType, new ArrayList<>());
}
private ArrayTypeName(TypeName componentType, List<AnnotationSpec> annotations) {
super(annotations);
this.componentType = checkNotNull(componentType, "rawType == null");
}
@Override public ArrayTypeName annotated(List<AnnotationSpec> annotations) {
return new ArrayTypeName(componentType, concatAnnotations(annotations));
}
@Override public TypeName withoutAnnotations() {
return new ArrayTypeName(componentType);
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
return emit(out, false);
}
CodeWriter emit(CodeWriter out, boolean varargs) throws IOException {
emitLeafType(out);
return emitBrackets(out, varargs);
}
private CodeWriter emitLeafType(CodeWriter out) throws IOException {
if (TypeName.asArray(componentType) != null) {
return TypeName.asArray(componentType).emitLeafType(out);
}
return componentType.emit(out);
}
private CodeWriter emitBrackets(CodeWriter out, boolean varargs) throws IOException {
if (isAnnotated()) {
out.emit(" ");
emitAnnotations(out);
}
if (TypeName.asArray(componentType) == null) {
// Last bracket.
return out.emit(varargs ? "..." : "[]");
}
out.emit("[]");
return TypeName.asArray(componentType) .emitBrackets(out, varargs);
}
/** Returns an array type whose elements are all instances of {@code componentType}.
public static ArrayTypeName of(TypeName componentType) {
return new ArrayTypeName(componentType);
}
/** Returns an array type whose elements are all instances of {@code componentType}.
public static ArrayTypeName of(Type componentType) {
return of(TypeName.get(componentType));
}
/** Returns an array type equivalent to {@code mirror}. | ArrayTypeName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/ArrayTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ArrayTypeName.java | Apache-2.0 |
public static ArrayTypeName get(GenericArrayType type) {
return get(type, new LinkedHashMap<>());
} | /*
Copyright (C) 2015 Square, Inc.
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.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.ArrayType;
import static com.squareup.javapoet.Util.checkNotNull;
public final class ArrayTypeName extends TypeName {
public final TypeName componentType;
private ArrayTypeName(TypeName componentType) {
this(componentType, new ArrayList<>());
}
private ArrayTypeName(TypeName componentType, List<AnnotationSpec> annotations) {
super(annotations);
this.componentType = checkNotNull(componentType, "rawType == null");
}
@Override public ArrayTypeName annotated(List<AnnotationSpec> annotations) {
return new ArrayTypeName(componentType, concatAnnotations(annotations));
}
@Override public TypeName withoutAnnotations() {
return new ArrayTypeName(componentType);
}
@Override CodeWriter emit(CodeWriter out) throws IOException {
return emit(out, false);
}
CodeWriter emit(CodeWriter out, boolean varargs) throws IOException {
emitLeafType(out);
return emitBrackets(out, varargs);
}
private CodeWriter emitLeafType(CodeWriter out) throws IOException {
if (TypeName.asArray(componentType) != null) {
return TypeName.asArray(componentType).emitLeafType(out);
}
return componentType.emit(out);
}
private CodeWriter emitBrackets(CodeWriter out, boolean varargs) throws IOException {
if (isAnnotated()) {
out.emit(" ");
emitAnnotations(out);
}
if (TypeName.asArray(componentType) == null) {
// Last bracket.
return out.emit(varargs ? "..." : "[]");
}
out.emit("[]");
return TypeName.asArray(componentType) .emitBrackets(out, varargs);
}
/** Returns an array type whose elements are all instances of {@code componentType}.
public static ArrayTypeName of(TypeName componentType) {
return new ArrayTypeName(componentType);
}
/** Returns an array type whose elements are all instances of {@code componentType}.
public static ArrayTypeName of(Type componentType) {
return of(TypeName.get(componentType));
}
/** Returns an array type equivalent to {@code mirror}.
public static ArrayTypeName get(ArrayType mirror) {
return get(mirror, new LinkedHashMap<>());
}
static ArrayTypeName get(
ArrayType mirror, Map<TypeParameterElement, TypeVariableName> typeVariables) {
return new ArrayTypeName(get(mirror.getComponentType(), typeVariables));
}
/** Returns an array type equivalent to {@code type}. | ArrayTypeName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/ArrayTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ArrayTypeName.java | Apache-2.0 |
public static WildcardTypeName subtypeOf(TypeName upperBound) {
return new WildcardTypeName(Collections.singletonList(upperBound), Collections.emptyList());
} |
Returns a type that represents an unknown type that extends {@code bound}. For example, if
{@code bound} is {@code CharSequence.class}, this returns {@code ? extends CharSequence}. If
{@code bound} is {@code Object.class}, this returns {@code ?}, which is shorthand for {@code
? extends Object}.
| WildcardTypeName::subtypeOf | java | square/javapoet | src/main/java/com/squareup/javapoet/WildcardTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/WildcardTypeName.java | Apache-2.0 |
public static WildcardTypeName supertypeOf(TypeName lowerBound) {
return new WildcardTypeName(Collections.singletonList(OBJECT),
Collections.singletonList(lowerBound));
} |
Returns a type that represents an unknown supertype of {@code bound}. For example, if {@code
bound} is {@code String.class}, this returns {@code ? super String}.
| WildcardTypeName::supertypeOf | java | square/javapoet | src/main/java/com/squareup/javapoet/WildcardTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/WildcardTypeName.java | Apache-2.0 |
public ParameterizedTypeName nestedClass(String name) {
checkNotNull(name, "name == null");
return new ParameterizedTypeName(this, rawType.nestedClass(name), new ArrayList<>(),
new ArrayList<>());
} |
Returns a new {@link ParameterizedTypeName} instance for the specified {@code name} as nested
inside this class.
| ParameterizedTypeName::nestedClass | java | square/javapoet | src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | Apache-2.0 |
public ParameterizedTypeName nestedClass(String name, List<TypeName> typeArguments) {
checkNotNull(name, "name == null");
return new ParameterizedTypeName(this, rawType.nestedClass(name), typeArguments,
new ArrayList<>());
} |
Returns a new {@link ParameterizedTypeName} instance for the specified {@code name} as nested
inside this class, with the specified {@code typeArguments}.
| ParameterizedTypeName::nestedClass | java | square/javapoet | src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | Apache-2.0 |
public static ParameterizedTypeName get(ClassName rawType, TypeName... typeArguments) {
return new ParameterizedTypeName(null, rawType, Arrays.asList(typeArguments));
} |
Returns a new {@link ParameterizedTypeName} instance for the specified {@code name} as nested
inside this class, with the specified {@code typeArguments}.
public ParameterizedTypeName nestedClass(String name, List<TypeName> typeArguments) {
checkNotNull(name, "name == null");
return new ParameterizedTypeName(this, rawType.nestedClass(name), typeArguments,
new ArrayList<>());
}
/** Returns a parameterized type, applying {@code typeArguments} to {@code rawType}. | ParameterizedTypeName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | Apache-2.0 |
public static ParameterizedTypeName get(Class<?> rawType, Type... typeArguments) {
return new ParameterizedTypeName(null, ClassName.get(rawType), list(typeArguments));
} |
Returns a new {@link ParameterizedTypeName} instance for the specified {@code name} as nested
inside this class, with the specified {@code typeArguments}.
public ParameterizedTypeName nestedClass(String name, List<TypeName> typeArguments) {
checkNotNull(name, "name == null");
return new ParameterizedTypeName(this, rawType.nestedClass(name), typeArguments,
new ArrayList<>());
}
/** Returns a parameterized type, applying {@code typeArguments} to {@code rawType}.
public static ParameterizedTypeName get(ClassName rawType, TypeName... typeArguments) {
return new ParameterizedTypeName(null, rawType, Arrays.asList(typeArguments));
}
/** Returns a parameterized type, applying {@code typeArguments} to {@code rawType}. | ParameterizedTypeName::get | java | square/javapoet | src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | https://github.com/square/javapoet/blob/master/src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | Apache-2.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.