001/*
002 * Copyright 2022-2025 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.soklet.core.impl;
018
019import com.soklet.core.InstanceProvider;
020
021import javax.annotation.Nonnull;
022import javax.annotation.concurrent.ThreadSafe;
023import java.lang.reflect.InvocationTargetException;
024
025import static java.lang.String.format;
026import static java.util.Objects.requireNonNull;
027
028/**
029 * @author <a href="https://www.revetkn.com">Mark Allen</a>
030 */
031@ThreadSafe
032public class DefaultInstanceProvider implements InstanceProvider {
033        @Nonnull
034        private static final DefaultInstanceProvider SHARED_INSTANCE;
035
036        static {
037                SHARED_INSTANCE = new DefaultInstanceProvider();
038        }
039
040        @Nonnull
041        public static DefaultInstanceProvider sharedInstance() {
042                return SHARED_INSTANCE;
043        }
044
045        @Nonnull
046        @Override
047        public <T> T provide(@Nonnull Class<T> instanceClass) {
048                requireNonNull(instanceClass);
049
050                try {
051                        return instanceClass.getDeclaredConstructor().newInstance();
052                } catch (NoSuchMethodException e) {
053                        throw new RuntimeException(format("Unable to create an instance of %s because no default constructor was found.", instanceClass), e);
054                } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
055                        throw new RuntimeException(format("Unable to create an instance of %s", instanceClass), e);
056                }
057        }
058}