You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JavaFileObjectClassLoader.java 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (C) 2012-present the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.pf4j.test;
  17. import javax.tools.JavaFileObject;
  18. import java.util.ArrayList;
  19. import java.util.Arrays;
  20. import java.util.Comparator;
  21. import java.util.HashMap;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.Objects;
  25. /**
  26. * {@link ClassLoader} that loads {@link JavaFileObject.Kind#CLASS}s.
  27. * If {@code JavaFileObject} type is {@link JavaFileObject.Kind#SOURCE} them the source is compiled.
  28. *
  29. * @author Decebal Suiu
  30. */
  31. public class JavaFileObjectClassLoader extends ClassLoader {
  32. public Map<String, Class<?>> load(JavaFileObject... objects) {
  33. return load(Arrays.asList(objects));
  34. }
  35. public Map<String, Class<?>> load(List<JavaFileObject> objects) {
  36. Objects.requireNonNull(objects);
  37. List<JavaFileObject> mutableObjects = new ArrayList<>(objects);
  38. // Sort generated ".class" by lastModified field
  39. mutableObjects.sort(Comparator.comparingLong(JavaFileObject::getLastModified));
  40. // Compile Java sources (if exists)
  41. for (int i = 0; i < mutableObjects.size(); i++) {
  42. JavaFileObject object = mutableObjects.get(i);
  43. if (object.getKind() == JavaFileObject.Kind.CLASS) {
  44. continue;
  45. }
  46. if (object.getKind() == JavaFileObject.Kind.SOURCE) {
  47. mutableObjects.set(i, JavaSources.compile(object));
  48. } else {
  49. throw new IllegalStateException("Type " + object.getKind() + " is not supported");
  50. }
  51. }
  52. // Load objects
  53. Map<String, Class<?>> loadedClasses = new HashMap<>();
  54. for (JavaFileObject object : mutableObjects) {
  55. String className = JavaFileObjectUtils.getClassName(object);
  56. byte[] data = JavaFileObjectUtils.getAllBytes(object);
  57. Class<?> loadedClass = defineClass(className, data, 0, data.length);
  58. loadedClasses.put(className, loadedClass);
  59. }
  60. return loadedClasses;
  61. }
  62. }