001 package de.deepamehta.core.impl; 002 003 import de.deepamehta.core.osgi.PluginContext; 004 import de.deepamehta.core.service.PluginService; 005 006 import java.lang.reflect.Field; 007 008 009 010 class InjectableService { 011 012 // ---------------------------------------------------------------------------------------------- Instance Variables 013 014 private PluginContext pluginContext; 015 private Class<? extends PluginService> serviceInterface; 016 private Field injectableField; 017 018 private boolean isServiceAvailable; 019 020 // ---------------------------------------------------------------------------------------------------- Constructors 021 022 InjectableService(PluginContext pluginContext, Class<? extends PluginService> serviceInterface, 023 Field injectableField) { 024 this.pluginContext = pluginContext; 025 this.serviceInterface = serviceInterface; 026 this.injectableField = injectableField; 027 // 028 injectableField.setAccessible(true); // allow injection into private fields 029 } 030 031 // -------------------------------------------------------------------------------------------------- Public Methods 032 033 @Override 034 public String toString() { 035 return serviceInterface.getName(); 036 } 037 038 // ----------------------------------------------------------------------------------------- Package Private Methods 039 040 Class<? extends PluginService> getServiceInterface() { 041 return serviceInterface; 042 } 043 044 boolean isServiceAvailable() { 045 return isServiceAvailable; 046 } 047 048 // --- 049 050 void injectService(Object service) { 051 injectValue(service); 052 isServiceAvailable = true; 053 } 054 055 void injectNull() { 056 injectValue(null); 057 isServiceAvailable = false; 058 } 059 060 // ------------------------------------------------------------------------------------------------- Private Methods 061 062 private void injectValue(Object value) { 063 try { 064 injectableField.set(pluginContext, value); // throws IllegalAccessException 065 } catch (Exception e) { 066 throw new RuntimeException("Injecting " + (value == null ? "null for " : "") + this + " failed", e); 067 } 068 } 069 }