DefaultInstantiator.java
01 /*
02  * SPDX-License-Identifier: Apache-2.0
03  *
04  * Copyright 2008-2017 the original author or authors.
05  *
06  * Licensed under the Apache License, Version 2.0 (the "License");
07  * you may not use this file except in compliance with the License.
08  * You may obtain a copy of the License at
09  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 package org.codehaus.griffon.runtime.util;
19 
20 import griffon.core.injection.Injector;
21 import griffon.exceptions.InstanceNotFoundException;
22 import griffon.util.Instantiator;
23 
24 import javax.annotation.Nonnull;
25 import javax.annotation.PostConstruct;
26 import javax.inject.Inject;
27 import javax.inject.Provider;
28 
29 import static griffon.util.GriffonClassUtils.invokeAnnotatedMethod;
30 import static java.util.Objects.requireNonNull;
31 
32 /**
33  @author Andres Almiray
34  @since 2.10.0
35  */
36 public class DefaultInstantiator implements Instantiator {
37     private final Provider<Injector> injector;
38 
39     @Inject
40     public DefaultInstantiator(@Nonnull Provider<Injector> injector) {
41         this.injector = requireNonNull(injector, "Argument 'injector' must not be null");
42     }
43 
44     @Override
45     public <T> T instantiate(@Nonnull Class<? extends T> klass) {
46         Injector injector = this.injector.get();
47 
48         if (injector != null) {
49             try {
50                 return (Tinjector.getInstance(klass);
51             catch (InstanceNotFoundException e) {
52                 return newInstanceFromClass(klass);
53             }
54         else {
55             return newInstanceFromClass(klass);
56         }
57     }
58 
59     @Nonnull
60     protected <T> T newInstanceFromClass(@Nonnull Class<? extends T> klass) {
61         try {
62             T instance = klass.newInstance();
63             Injector injector = this.injector.get();
64             if (injector != null) {
65                 injector.injectMembers(instance);
66                 invokeAnnotatedMethod(instance, PostConstruct.class);
67             }
68             return instance;
69         catch (InstantiationException | IllegalAccessException e) {
70             throw new IllegalStateException(e);
71         }
72     }
73 }