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.

DefaultPluginFactory.java 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright 2014 Decebal Suiu
  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;
  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;
  19. import java.lang.reflect.Constructor;
  20. import java.lang.reflect.Modifier;
  21. /**
  22. * The default implementation for {@link PluginFactory}.
  23. * It uses {@link Class#newInstance()} method.
  24. *
  25. * @author Decebal Suiu
  26. */
  27. public class DefaultPluginFactory implements PluginFactory {
  28. private static final Logger log = LoggerFactory.getLogger(DefaultExtensionFactory.class);
  29. /**
  30. * Creates a plugin instance. If an error occurs than that error is logged and the method returns null.
  31. * @param pluginWrapper
  32. * @return
  33. */
  34. @Override
  35. public Plugin create(final PluginWrapper pluginWrapper) {
  36. String pluginClassName = pluginWrapper.getDescriptor().getPluginClass();
  37. log.debug("Create instance for plugin '{}'", pluginClassName);
  38. Class<?> pluginClass;
  39. try {
  40. pluginClass = pluginWrapper.getPluginClassLoader().loadClass(pluginClassName);
  41. } catch (ClassNotFoundException e) {
  42. log.error(e.getMessage(), e);
  43. return null;
  44. }
  45. // once we have the class, we can do some checks on it to ensure
  46. // that it is a valid implementation of a plugin.
  47. int modifiers = pluginClass.getModifiers();
  48. if (Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers)
  49. || (!Plugin.class.isAssignableFrom(pluginClass))) {
  50. log.error("The plugin class '{}' is not valid", pluginClassName);
  51. return null;
  52. }
  53. // create the plugin instance
  54. try {
  55. Constructor<?> constructor = pluginClass.getConstructor(PluginWrapper.class);
  56. return (Plugin) constructor.newInstance(pluginWrapper);
  57. } catch (Exception e) {
  58. log.error(e.getMessage(), e);
  59. }
  60. return null;
  61. }
  62. }