001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.commons.conversion; 018 019import static org.apache.juneau.commons.reflect.ReflectionUtils.*; 020import static org.apache.juneau.commons.utils.Shorts.*; 021import static org.apache.juneau.commons.utils.StringUtils.*; 022 023import java.lang.reflect.*; 024import java.math.*; 025import java.nio.charset.*; 026import java.util.*; 027import java.util.concurrent.atomic.*; 028 029import org.apache.juneau.commons.reflect.*; 030 031/** 032 * A concrete {@link CachingConverter} that supports common type conversions without 033 * requiring a {@code MarshallingContext} or {@code MarshallingSession}. 034 * 035 * <p> 036 * The following conversions are supported: 037 * 038 * <table class='styled'> 039 * <caption>Supported conversions</caption> 040 * <tr><th>Input type</th><th>Output type</th><th>Notes</th></tr> 041 * <tr> 042 * <td>Any type</td> 043 * <td>Same or supertype</td> 044 * <td>Identity / widening (no-op cast)</td> 045 * </tr> 046 * <tr> 047 * <td>{@link Number}</td> 048 * <td> 049 * {@link Integer}, {@link Long}, {@link Short}, {@link Float}, {@link Double}, {@link Byte}, 050 * {@link AtomicInteger}, {@link AtomicLong}, {@link BigDecimal}, {@link BigInteger}, 051 * and primitive equivalents 052 * </td> 053 * <td>Narrowing/widening numeric conversion</td> 054 * </tr> 055 * <tr> 056 * <td>{@link Boolean}</td> 057 * <td>{@link Number} types (including {@link BigDecimal}, {@link BigInteger})</td> 058 * <td><c>true=1, false=0</c></td> 059 * </tr> 060 * <tr> 061 * <td>{@link CharSequence}</td> 062 * <td>{@link Number} types</td> 063 * <td>Parsed via {@link org.apache.juneau.commons.utils.StringUtils#parseNumber(String, Class)}; 064 * empty string or {@code "null"} returns <jk>null</jk></td> 065 * </tr> 066 * <tr> 067 * <td>{@link Number}</td> 068 * <td>{@link Boolean}</td> 069 * <td><c>intValue() != 0</c></td> 070 * </tr> 071 * <tr> 072 * <td>{@link CharSequence}</td> 073 * <td>{@link Boolean}</td> 074 * <td>{@link Boolean#valueOf(String)}</td> 075 * </tr> 076 * <tr> 077 * <td>{@link CharSequence} (length 1)</td> 078 * <td>{@link Character}</td> 079 * <td><c>charAt(0)</c></td> 080 * </tr> 081 * <tr> 082 * <td>{@link Number}</td> 083 * <td>{@link Character}</td> 084 * <td>First character of {@code toString()} (e.g. {@code 65} → {@code '6'})</td> 085 * </tr> 086 * <tr> 087 * <td>Any</td> 088 * <td>{@link String}</td> 089 * <td>{@link Object#toString()}, with array support via {@link Arrays#toString(Object[])}</td> 090 * </tr> 091 * <tr> 092 * <td>{@link CharSequence}</td> 093 * <td>{@code byte[]}</td> 094 * <td>UTF-8 encoding via {@link String#getBytes(Charset)}</td> 095 * </tr> 096 * <tr> 097 * <td>{@link CharSequence}</td> 098 * <td>Any {@link Enum}</td> 099 * <td>{@link Enum#valueOf(Class, String)}</td> 100 * </tr> 101 * <tr> 102 * <td>{@link Collection} or array</td> 103 * <td>{@link Collection} subtype</td> 104 * <td>Copies elements; element type from <c>args[0]</c></td> 105 * </tr> 106 * <tr> 107 * <td>{@link Map}</td> 108 * <td>{@link Map} subtype</td> 109 * <td>Copies entries; key type from <c>args[0]</c>, value type from <c>args[1]</c></td> 110 * </tr> 111 * <tr> 112 * <td>{@link Collection} or array</td> 113 * <td>Array type</td> 114 * <td>Element type from <c>outType.getComponentType()</c></td> 115 * </tr> 116 * <tr> 117 * <td>{@link String}</td> 118 * <td>{@link TimeZone}</td> 119 * <td>{@link TimeZone#getTimeZone(String)}</td> 120 * </tr> 121 * <tr> 122 * <td>{@link TimeZone}</td> 123 * <td>{@link String}</td> 124 * <td>{@link TimeZone#getID()}</td> 125 * </tr> 126 * <tr> 127 * <td>{@link String}</td> 128 * <td>{@link Locale}</td> 129 * <td>{@link Locale#forLanguageTag(String)} (underscores converted to hyphens)</td> 130 * </tr> 131 * <tr> 132 * <td>Any</td> 133 * <td>Any with <c>static T fromString/valueOf/of/from/parse/create/forName/fromValue/builder(X)</c> 134 * or dynamic <c>fromX/forX/parseX</c> where X is the input class name</td> 135 * <td>Reflection-based static factory lookup</td> 136 * </tr> 137 * <tr> 138 * <td>Any</td> 139 * <td>Any with <c>public T(X)</c> constructor</td> 140 * <td>Reflection-based constructor lookup</td> 141 * </tr> 142 * <tr> 143 * <td>Any with <c>toX()</c> instance method</td> 144 * <td>Any type X</td> 145 * <td>Instance method where name matches <c>to</c> + output class name (e.g. <c>toInteger()</c>)</td> 146 * </tr> 147 * </table> 148 * 149 * <h2 class='section'>Thread Safety:</h2> 150 * <p> 151 * This class is thread-safe. The singleton instance can be safely shared across multiple threads. 152 */ 153@SuppressWarnings({ 154 "java:S1067", // Complex boolean expressions in conversion checks reflect the natural type hierarchy 155 "java:S1192", // "parse" literal is used in multiple independent Sets/arrays; extracting it would reduce clarity 156 "java:S3776", // Cognitive complexity of conversion dispatch methods is inherent to the number of supported type pairs 157 "rawtypes", // Raw types necessary for generic conversion dispatch 158 "unchecked" // Type erasure requires unchecked casts throughout conversion logic 159}) 160public class BasicConverter extends CachingConverter { 161 162 /** 163 * Singleton instance. 164 */ 165 public static final BasicConverter INSTANCE = new BasicConverter(); 166 167 private static final Set<String> FACTORY_METHOD_NAMES = Set.of( 168 "fromString", "valueOf", "of", "from", "parse", "create", "forName", "fromValue", "builder" 169 ); 170 171 private static final Map<Class<?>,Class<?>> PRIMITIVE_TO_WRAPPER = Map.of( 172 boolean.class, Boolean.class, 173 byte.class, Byte.class, 174 char.class, Character.class, 175 double.class, Double.class, 176 float.class, Float.class, 177 int.class, Integer.class, 178 long.class, Long.class, 179 short.class, Short.class 180 ); 181 182 /** 183 * Constructor. 184 */ 185 protected BasicConverter() {} 186 187 @Override 188 protected <I,O> Conversion<I,O> findConversion(Class<I> inType, Class<O> outType) { 189 var out = outType.isPrimitive() ? (Class<O>) PRIMITIVE_TO_WRAPPER.get(outType) : outType; 190 191 Conversion<I,O> c; 192 193 if ((c = findSpecialConversion(inType, out)) != null) return c; 194 195 if (out.isAssignableFrom(inType) && !Collection.class.isAssignableFrom(out) && !Map.class.isAssignableFrom(out)) 196 return (in, memberOf, session, args) -> (O) in; 197 198 if (Number.class.isAssignableFrom(out) && (c = findNumberConversion(inType, out)) != null) return c; 199 200 if (out == Boolean.class && (c = findBooleanConversion(inType)) != null) return c; 201 202 if (out == Character.class && (c = findCharacterConversion(inType)) != null) return c; 203 204 if (out == String.class) 205 return (Conversion<I,O>) findToStringConversion(inType); 206 207 if (out.isEnum() && (c = findEnumConversion(inType, out)) != null) return c; 208 209 if (out == Optional.class && (c = findOptionalConversion()) != null) return c; 210 211 if ((out == OptionalInt.class || out == OptionalLong.class || out == OptionalDouble.class) 212 && (c = findPrimitiveOptionalConversion(out)) != null) return c; 213 214 if (Collection.class.isAssignableFrom(out) && (c = findCollectionConversion(inType, out)) != null) return c; 215 216 if (Map.class.isAssignableFrom(out) && (c = findMapConversion(inType, out)) != null) return c; 217 218 if (out.isArray() && (c = findArrayConversion(inType, out)) != null) return c; 219 220 if ((c = findToXMethod(inType, out)) != null) return c; 221 222 if ((c = findStaticFactory(inType, out)) != null) return c; 223 224 if ((c = findConstructorConversion(inType, out)) != null) return c; 225 226 return null; 227 } 228 229 //----------------------------------------------------------------------------------------------------------------- 230 // Number conversions 231 //----------------------------------------------------------------------------------------------------------------- 232 233 private <I,O> Conversion<I,O> findNumberConversion(Class<I> inType, Class<O> outType) { 234 if (Number.class.isAssignableFrom(inType)) 235 return findNumberFromNumber(outType); 236 if (inType == Boolean.class) 237 return (Conversion<I,O>) findNumberFromBoolean(outType); 238 if (CharSequence.class.isAssignableFrom(inType)) 239 return (Conversion<I,O>) findNumberFromString(outType); 240 return null; 241 } 242 243 private <I,O> Conversion<I,O> findNumberFromNumber(Class<O> outType) { 244 if (outType == Integer.class) return (in, memberOf, session, args) -> (O) Integer.valueOf(((Number) in).intValue()); 245 if (outType == Long.class) return (in, memberOf, session, args) -> (O) Long.valueOf(((Number) in).longValue()); 246 if (outType == Short.class) return (in, memberOf, session, args) -> (O) Short.valueOf(((Number) in).shortValue()); 247 if (outType == Float.class) return (in, memberOf, session, args) -> (O) Float.valueOf(((Number) in).floatValue()); 248 if (outType == Double.class) return (in, memberOf, session, args) -> (O) Double.valueOf(((Number) in).doubleValue()); 249 if (outType == Byte.class) return (in, memberOf, session, args) -> (O) Byte.valueOf(((Number) in).byteValue()); 250 if (outType == AtomicInteger.class) return (in, memberOf, session, args) -> (O) new AtomicInteger(((Number) in).intValue()); 251 if (outType == AtomicLong.class) return (in, memberOf, session, args) -> (O) new AtomicLong(((Number) in).longValue()); 252 if (outType == BigDecimal.class) return (in, memberOf, session, args) -> (O) parseBigDecimal(in.toString()); 253 if (outType == BigInteger.class) return (in, memberOf, session, args) -> { 254 var n = (Number) in; 255 if (n instanceof BigDecimal n2) return (O) n2.toBigInteger(); 256 if (n instanceof BigInteger n2) return (O) n2; 257 return (O) BigInteger.valueOf(n.longValue()); 258 }; 259 return null; 260 } 261 262 private <O> Conversion<Boolean,O> findNumberFromBoolean(Class<O> outType) { 263 if (outType == Integer.class) return (in, memberOf, session, args) -> (O) Integer.valueOf(in.booleanValue() ? 1 : 0); 264 if (outType == Long.class) return (in, memberOf, session, args) -> (O) Long.valueOf(in.booleanValue() ? 1L : 0L); 265 if (outType == Short.class) return (in, memberOf, session, args) -> (O) Short.valueOf(in.booleanValue() ? (short) 1 : (short) 0); 266 if (outType == Float.class) return (in, memberOf, session, args) -> (O) Float.valueOf(in.booleanValue() ? 1f : 0f); 267 if (outType == Double.class) return (in, memberOf, session, args) -> (O) Double.valueOf(in.booleanValue() ? 1d : 0d); 268 if (outType == Byte.class) return (in, memberOf, session, args) -> (O) Byte.valueOf(in.booleanValue() ? (byte) 1 : (byte) 0); 269 if (outType == AtomicInteger.class) return (in, memberOf, session, args) -> (O) new AtomicInteger(in.booleanValue() ? 1 : 0); 270 if (outType == AtomicLong.class) return (in, memberOf, session, args) -> (O) new AtomicLong(in.booleanValue() ? 1L : 0L); 271 if (outType == BigDecimal.class) return (in, memberOf, session, args) -> (O) BigDecimal.valueOf(in.booleanValue() ? 1L : 0L); 272 if (outType == BigInteger.class) return (in, memberOf, session, args) -> (O) BigInteger.valueOf(in.booleanValue() ? 1L : 0L); 273 return null; 274 } 275 276 private <O> Conversion<CharSequence,O> findNumberFromString(Class<O> outType) { 277 return (in, memberOf, session, args) -> { 278 var s = in.toString(); 279 if (s.isEmpty() || eq(s, "null")) 280 return null; 281 return (O) parseNumber(s, (Class<? extends Number>) outType); 282 }; 283 } 284 285 //----------------------------------------------------------------------------------------------------------------- 286 // Boolean conversions 287 //----------------------------------------------------------------------------------------------------------------- 288 289 private <I,O> Conversion<I,O> findBooleanConversion(Class<I> inType) { 290 if (Number.class.isAssignableFrom(inType)) 291 return (in, memberOf, session, args) -> (O) Boolean.valueOf(((Number) in).intValue() != 0); 292 return null; 293 } 294 295 //----------------------------------------------------------------------------------------------------------------- 296 // Character conversions 297 //----------------------------------------------------------------------------------------------------------------- 298 299 private <I,O> Conversion<I,O> findCharacterConversion(Class<I> inType) { 300 if (CharSequence.class.isAssignableFrom(inType)) 301 return (in, memberOf, session, args) -> { 302 var s = in.toString(); 303 if (s.length() != 1) 304 throw iaex("Cannot convert string of length %s to char: '%s'", s.length(), s); 305 return (O) Character.valueOf(s.charAt(0)); 306 }; 307 if (Number.class.isAssignableFrom(inType)) 308 return (in, memberOf, session, args) -> { 309 var s = in.toString(); 310 return s.isEmpty() ? null : (O) Character.valueOf(s.charAt(0)); 311 }; 312 return null; 313 } 314 315 //----------------------------------------------------------------------------------------------------------------- 316 // String conversions 317 //----------------------------------------------------------------------------------------------------------------- 318 319 private <I> Conversion<I,String> findToStringConversion(Class<I> inType) { 320 if (inType.isArray()) { 321 if (inType == int[].class) return (in, memberOf, session, args) -> Arrays.toString((int[]) in); 322 if (inType == long[].class) return (in, memberOf, session, args) -> Arrays.toString((long[]) in); 323 if (inType == double[].class) return (in, memberOf, session, args) -> Arrays.toString((double[]) in); 324 if (inType == float[].class) return (in, memberOf, session, args) -> Arrays.toString((float[]) in); 325 if (inType == boolean[].class) return (in, memberOf, session, args) -> Arrays.toString((boolean[]) in); 326 if (inType == byte[].class) return (in, memberOf, session, args) -> Arrays.toString((byte[]) in); 327 if (inType == short[].class) return (in, memberOf, session, args) -> Arrays.toString((short[]) in); 328 if (inType == char[].class) return (in, memberOf, session, args) -> Arrays.toString((char[]) in); 329 return (in, memberOf, session, args) -> Arrays.deepToString((Object[]) in); 330 } 331 return (in, memberOf, session, args) -> in.toString(); 332 } 333 334 //----------------------------------------------------------------------------------------------------------------- 335 // Enum conversions 336 //----------------------------------------------------------------------------------------------------------------- 337 338 private <I,O> Conversion<I,O> findEnumConversion(Class<I> inType, Class<O> outType) { 339 if (CharSequence.class.isAssignableFrom(inType)) 340 return (in, memberOf, session, args) -> (O) Enum.valueOf((Class<Enum>) outType, in.toString()); 341 return null; 342 } 343 344 //----------------------------------------------------------------------------------------------------------------- 345 // Optional conversions 346 //----------------------------------------------------------------------------------------------------------------- 347 348 private <I,O> Conversion<I,O> findOptionalConversion() { 349 return (Conversion<I,O>) (Conversion<Object,Optional<?>>) (in, memberOf, session, args) -> { 350 if (in instanceof Optional<?> in2) { 351 if (args.length == 0) 352 return in2; 353 return in2.map(x -> to(x, memberOf, session, args[0])); 354 } 355 if (args.length == 0) 356 return o(in); 357 return o(to(in, memberOf, session, args[0])); 358 }; 359 } 360 361 /** 362 * Conversion to a primitive {@link OptionalInt}/{@link OptionalLong}/{@link OptionalDouble}. 363 * 364 * <p> 365 * Mirrors the {@link Optional} contract: a {@code null} input (or an empty optional of any flavor) 366 * yields the matching empty primitive optional; any other value is unwrapped (if it is itself an 367 * optional) and coerced to the matching boxed number before wrapping. 368 * 369 * @param out The target primitive-optional class. 370 * @return The conversion, never <jk>null</jk>. 371 */ 372 private <I,O> Conversion<I,O> findPrimitiveOptionalConversion(Class<O> out) { 373 final Class<? extends Number> elementType; 374 if (out == OptionalInt.class) 375 elementType = Integer.class; 376 else if (out == OptionalLong.class) 377 elementType = Long.class; 378 else 379 elementType = Double.class; 380 return (Conversion<I,O>) (Conversion<Object,Object>) (in, memberOf, session, args) -> { 381 Object v = in; 382 if (v instanceof Optional<?> v2) 383 v = v2.orElse(null); 384 else if (v instanceof OptionalInt v3) 385 v = v3.isPresent() ? Integer.valueOf(v3.getAsInt()) : null; 386 else if (v instanceof OptionalLong v4) 387 v = v4.isPresent() ? Long.valueOf(v4.getAsLong()) : null; 388 else if (v instanceof OptionalDouble v5) 389 v = v5.isPresent() ? Double.valueOf(v5.getAsDouble()) : null; 390 if (v == null) 391 return emptyPrimitiveOptional(out); 392 var n = (Number) to(v, memberOf, session, elementType); 393 if (n == null) 394 return emptyPrimitiveOptional(out); 395 if (out == OptionalInt.class) 396 return OptionalInt.of(n.intValue()); 397 if (out == OptionalLong.class) 398 return OptionalLong.of(n.longValue()); 399 return OptionalDouble.of(n.doubleValue()); 400 }; 401 } 402 403 private static Object emptyPrimitiveOptional(Class<?> out) { 404 if (out == OptionalInt.class) 405 return OptionalInt.empty(); 406 if (out == OptionalLong.class) 407 return OptionalLong.empty(); 408 return OptionalDouble.empty(); 409 } 410 411 //----------------------------------------------------------------------------------------------------------------- 412 // Collection conversions 413 //----------------------------------------------------------------------------------------------------------------- 414 415 private <I,O> Conversion<I,O> findCollectionConversion(Class<I> inType, Class<O> outType) { 416 if (Collection.class.isAssignableFrom(inType) || inType.isArray()) { 417 return (in, memberOf, session, args) -> { 418 // Treat Object.class as "no element type" since it means untyped/raw and needs no element conversion. 419 var elemType = args.length > 0 && args[0] != Object.class ? args[0] : null; 420 if (elemType == null && !inType.isArray() && outType.isAssignableFrom(inType)) 421 return (O) in; 422 var result = newCollection(outType); 423 if (Collection.class.isAssignableFrom(inType)) { 424 for (var elem : (Collection<?>) in) 425 result.add(elemType != null ? to(elem, elemType) : elem); 426 } else { 427 var len = Array.getLength(in); 428 for (var i = 0; i < len; i++) { 429 var elem = Array.get(in, i); 430 result.add(elemType != null ? to(elem, elemType) : elem); 431 } 432 } 433 return (O) result; 434 }; 435 } 436 return null; 437 } 438 439 private Collection<Object> newCollection(Class<?> outType) { 440 if (outType == List.class || outType == Collection.class || outType == Iterable.class /* HTT: Iterable is a supertype of Collection so findCollectionConversion never passes Iterable as outType */ || outType == AbstractList.class) 441 return l(); 442 if (outType == Set.class || outType == LinkedHashSet.class || outType == AbstractSet.class) 443 return st(); 444 if (outType == SortedSet.class || outType == NavigableSet.class || outType == TreeSet.class) 445 return new TreeSet<>(); 446 if (outType == Queue.class || outType == Deque.class || outType == LinkedList.class) 447 return new LinkedList<>(); 448 return newInstanceOrDefault(outType, ArrayList::new); 449 } 450 451 //----------------------------------------------------------------------------------------------------------------- 452 // Map conversions 453 //----------------------------------------------------------------------------------------------------------------- 454 455 private <I,O> Conversion<I,O> findMapConversion(Class<I> inType, Class<O> outType) { 456 if (Map.class.isAssignableFrom(inType)) { 457 return (in, memberOf, session, args) -> { 458 // Treat Object.class as "no key/value type" since it means untyped/raw and needs no element conversion. 459 var keyType = args.length > 0 && args[0] != Object.class ? args[0] : null; 460 var valType = args.length > 1 && args[1] != Object.class ? args[1] : null; 461 if (keyType == null && outType.isAssignableFrom(inType)) 462 return (O) in; 463 var result = newMap(outType); 464 ((Map<?,?>) in).forEach((k, v) -> result.put( 465 keyType != null ? to(k, keyType) : k, 466 valType != null ? to(v, valType) : v 467 )); 468 return (O) result; 469 }; 470 } 471 return null; 472 } 473 474 private Map<Object,Object> newMap(Class<?> outType) { 475 if (outType == Map.class || outType == LinkedHashMap.class || outType == AbstractMap.class) 476 return m(); 477 if (outType == SortedMap.class || outType == NavigableMap.class || outType == TreeMap.class) 478 return new TreeMap<>(); 479 if (outType == HashMap.class) 480 return new HashMap<>(); 481 return newInstanceOrDefault(outType, LinkedHashMap::new); 482 } 483 484 //----------------------------------------------------------------------------------------------------------------- 485 // Array conversions 486 //----------------------------------------------------------------------------------------------------------------- 487 488 private <I,O> Conversion<I,O> findArrayConversion(Class<I> inType, Class<O> outType) { 489 if (Collection.class.isAssignableFrom(inType) || inType.isArray()) { 490 var componentType = outType.getComponentType(); 491 // For array→array, validate that element-level conversion is possible. 492 // Skip the pre-check for Object[] — runtime elements may be of a more specific type. 493 // Collections use runtime element types so we skip the pre-check there too. 494 if (inType.isArray()) { 495 var inComponentType = inType.getComponentType(); 496 // Primitive component types are auto-boxed by Array.get(), so skip the canConvert check. 497 // Otherwise verify that element-level conversion is possible before returning a lambda. 498 if (!inComponentType.isPrimitive() 499 && inComponentType != componentType 500 && inComponentType != Object.class 501 && !canConvert(inComponentType, componentType)) 502 return null; 503 } 504 return (in, memberOf, session, args) -> { 505 if (Collection.class.isAssignableFrom(inType)) { 506 var list = (Collection<?>) in; 507 var arr = Array.newInstance(componentType, list.size()); 508 var i = 0; 509 for (var elem : list) 510 Array.set(arr, i++, to(elem, memberOf, session, componentType)); 511 return (O) arr; 512 } 513 var len = Array.getLength(in); 514 var arr = Array.newInstance(componentType, len); 515 for (var i = 0; i < len; i++) 516 Array.set(arr, i, to(Array.get(in, i), memberOf, session, componentType)); 517 return (O) arr; 518 }; 519 } 520 return null; 521 } 522 523 //----------------------------------------------------------------------------------------------------------------- 524 // Special-case conversions 525 //----------------------------------------------------------------------------------------------------------------- 526 527 /** 528 * Resolves a class name without running its static initializer. 529 * 530 * <p> 531 * {@link Class#forName(String)} initializes the class, which would let an input string trigger arbitrary 532 * static-initializer code, so the three-argument form with {@code initialize=false} is used instead. 533 */ 534 private static Class<?> loadClassWithoutInit(String name) { 535 var cl = Thread.currentThread().getContextClassLoader(); 536 if (cl == null) 537 cl = BasicConverter.class.getClassLoader(); 538 try { 539 return Class.forName(name, false, cl); 540 } catch (ClassNotFoundException e) { 541 throw new IllegalArgumentException("Class not found: " + name, e); 542 } 543 } 544 545 private <I,O> Conversion<I,O> findSpecialConversion(Class<I> inType, Class<O> outType) { 546 if (inType == String.class && outType == TimeZone.class) 547 return (Conversion<I,O>) (Conversion<String,TimeZone>) (in, memberOf, session, args) -> TimeZone.getTimeZone(in); 548 if (TimeZone.class.isAssignableFrom(inType) && outType == String.class) 549 return (Conversion<I,O>) (Conversion<TimeZone,String>) (in, memberOf, session, args) -> in.getID(); 550 if (inType == String.class && outType == Class.class) 551 return (Conversion<I,O>) (Conversion<String,Class<?>>) (in, memberOf, session, args) -> loadClassWithoutInit(in); 552 if (inType == String.class && outType == Locale.class) 553 return (Conversion<I,O>) (Conversion<String,Locale>) (in, memberOf, session, args) -> Locale.forLanguageTag(in.replace('_', '-')); 554 if (CharSequence.class.isAssignableFrom(inType) && outType == Boolean.class) 555 return (in, memberOf, session, args) -> { 556 var s = in.toString(); 557 if (s.isEmpty() || eq(s, "null")) 558 return null; 559 return (O) Boolean.valueOf(s); 560 }; 561 if (CharSequence.class.isAssignableFrom(inType) && outType == byte[].class) 562 return (in, memberOf, session, args) -> (O) in.toString().getBytes(StandardCharsets.UTF_8); 563 return null; 564 } 565 566 //----------------------------------------------------------------------------------------------------------------- 567 // Reflection: static factory methods 568 //----------------------------------------------------------------------------------------------------------------- 569 570 private <I,O> Conversion<I,O> findStaticFactory(Class<I> inType, Class<O> outType) { 571 var ci = info(outType); 572 573 for (var name : FACTORY_METHOD_NAMES) { 574 var opt = findStaticMethod(ci, name, inType, outType); 575 if (opt.isPresent()) 576 return (in, memberOf, session, args) -> opt.get().invoke(null, in); 577 } 578 579 // Walk the type hierarchy (superclasses then interfaces) so that e.g. InputStreamReader 580 // can be passed to a method declared as fromReader(Reader r). 581 for (Class<?> c = inType; c != null && c != Object.class; c = c.getSuperclass()) { 582 var inName = c.getSimpleName(); 583 for (var prefix : new String[]{"from", "for", "parse"}) { 584 var opt = findStaticMethod(ci, prefix + inName, inType, outType); 585 if (opt.isPresent()) 586 return (in, memberOf, session, args) -> opt.get().invoke(null, in); 587 } 588 } 589 for (var iface : allInterfaces(inType)) { 590 var inName = iface.getSimpleName(); 591 for (var prefix : new String[]{"from", "for", "parse"}) { 592 var opt = findStaticMethod(ci, prefix + inName, inType, outType); 593 if (opt.isPresent()) 594 return (in, memberOf, session, args) -> opt.get().invoke(null, in); 595 } 596 } 597 598 return null; 599 } 600 601 private static List<Class<?>> allInterfaces(Class<?> c) { 602 var result = new ArrayList<Class<?>>(); 603 for (var x = c; x != null; x = x.getSuperclass()) 604 for (var iface : x.getInterfaces()) 605 collectInterfaces(iface, result); 606 return result; 607 } 608 609 private static void collectInterfaces(Class<?> iface, List<Class<?>> result) { 610 if (!result.contains(iface)) { 611 result.add(iface); 612 for (var parent : iface.getInterfaces()) 613 collectInterfaces(parent, result); 614 } 615 } 616 617 private Optional<MethodInfo> findStaticMethod(ClassInfo ci, String name, Class<?> inType, Class<?> outType) { 618 return ci.getPublicMethod(m -> 619 m.isStatic() 620 && m.isNotDeprecated() 621 && m.hasName(name) 622 && m.getParameterCount() == 1 623 && m.getParameterTypes().get(0).isAssignableFrom(inType) 624 && m.hasReturnTypeParent(outType) 625 // Exclude generic Object-param factory methods (e.g. List.of(E)) when input is not Object, 626 // since type erasure makes E appear as Object at runtime, causing false matches. 627 && (inType == Object.class || m.getParameterTypes().get(0).inner() != Object.class) 628 ); 629 } 630 631 //----------------------------------------------------------------------------------------------------------------- 632 // Reflection: public constructors 633 //----------------------------------------------------------------------------------------------------------------- 634 635 private <I,O> Conversion<I,O> findConstructorConversion(Class<I> inType, Class<O> outType) { 636 if (outType.getEnclosingClass() != null && !Modifier.isStatic(outType.getModifiers())) { 637 var enclosing = outType.getEnclosingClass(); 638 var opt = info(outType).getPublicConstructor(c -> 639 c.getParameterCount() == 2 640 && c.isNotDeprecated() 641 && c.getParameterTypes().get(0).inner() == enclosing 642 && c.getParameterTypes().get(1).isAssignableFrom(inType) 643 ); 644 if (opt.isPresent()) { 645 var ctor = opt.get(); 646 return (in, memberOf, session, args) -> ctor.newInstance(memberOf, in); 647 } 648 } 649 650 var opt = info(outType).getPublicConstructor(c -> 651 c.getParameterCount() == 1 652 && c.isNotDeprecated() 653 && c.getParameterTypes().get(0).isAssignableFrom(inType) 654 ); 655 if (opt.isPresent()) { 656 var ctor = opt.get(); 657 return (in, memberOf, session, args) -> ctor.newInstance(in); 658 } 659 return null; 660 } 661 662 //----------------------------------------------------------------------------------------------------------------- 663 // Reflection: toX() instance methods 664 //----------------------------------------------------------------------------------------------------------------- 665 666 private <I,O> Conversion<I,O> findToXMethod(Class<I> inType, Class<O> outType) { 667 // Use getNameReadable() so that array types use "Array" suffix (e.g. "toStringArray" for String[]). 668 // Use equalsIgnoreCase to match Mutaters' behavior (e.g. "toByteArray" matches "tobyteArray" from byte[]). 669 var methodName = "to" + info(outType).getNameReadable(); 670 var opt = info(inType).getPublicMethod(m -> 671 m.isNotStatic() 672 && m.isNotDeprecated() 673 && m.getParameterCount() == 0 674 && eqic(m.getNameSimple(), methodName) 675 && m.hasReturnTypeParent(outType) 676 ); 677 if (opt.isPresent()) { 678 var method = opt.get(); 679 return (in, memberOf, session, args) -> method.invoke(in); 680 } 681 return null; 682 } 683 684 //----------------------------------------------------------------------------------------------------------------- 685 // Helpers 686 //----------------------------------------------------------------------------------------------------------------- 687 688 private <T> T newInstanceOrDefault(Class<?> type, java.util.function.Supplier<T> defaultSupplier) { 689 var opt = info(type).getPublicConstructor(c -> c.getParameterCount() == 0); 690 if (opt.isPresent()) { 691 var ctor = opt.get(); 692 try { 693 return ctor.newInstance(); 694 } catch (@SuppressWarnings("unused") Exception e) { // HTT: constructor would have to throw to reach here 695 return defaultSupplier.get(); // HTT 696 } 697 } 698 return defaultSupplier.get(); 699 } 700}