您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JavaFileObjectDataProvider.java 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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.FileObject;
  18. import javax.tools.JavaFileObject;
  19. import java.util.ArrayList;
  20. import java.util.List;
  21. import java.util.Map;
  22. import java.util.stream.Collectors;
  23. /**
  24. * Get class data from {@link JavaFileObject}.
  25. * If {@code JavaFileObject} type is {@link JavaFileObject.Kind#SOURCE} them the source is compiled.
  26. *
  27. * @author Decebal Suiu
  28. */
  29. public class JavaFileObjectDataProvider implements ClassDataProvider {
  30. private final Map<String, JavaFileObject> classes;
  31. public JavaFileObjectDataProvider(Map<String, JavaFileObject> classes) {
  32. this.classes = classes;
  33. }
  34. public static JavaFileObjectDataProvider of(List<JavaFileObject> objects) {
  35. List<JavaFileObject> tmp = new ArrayList<>(objects.size());
  36. for (JavaFileObject object : objects) {
  37. if (object.getKind() == JavaFileObject.Kind.CLASS) {
  38. tmp.add(object);
  39. } else if (object.getKind() == JavaFileObject.Kind.SOURCE) {
  40. tmp.add(JavaSources.compile(object));
  41. } else {
  42. throw new IllegalStateException("Type " + object.getKind() + " is not supported");
  43. }
  44. }
  45. // TODO JavaFileObjectUtils.getClassName() ?!
  46. Map<String, JavaFileObject> classes = tmp.stream().collect(Collectors.toMap(FileObject::getName, c -> c));
  47. return new JavaFileObjectDataProvider(classes);
  48. }
  49. @Override
  50. public byte[] getClassData(String className) {
  51. return JavaFileObjectUtils.getAllBytes(classes.get(className));
  52. }
  53. }