001/* -*- mode: Java; c-basic-offset: 2; indent-tabs-mode: nil; coding: utf-8-unix -*- 002 * 003 * Copyright © 2024 microBean™. 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 006 * the License. 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 distributed under the License is distributed on 011 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the 012 * specific language governing permissions and limitations under the License. 013 */ 014package org.microbean.bean; 015 016import java.lang.constant.ClassDesc; 017import java.lang.constant.Constable; 018import java.lang.constant.DynamicConstantDesc; 019import java.lang.constant.MethodHandleDesc; 020 021import java.util.Objects; 022import java.util.Optional; 023 024import org.microbean.constant.Constables; 025 026import static java.lang.constant.ConstantDescs.BSM_INVOKE; 027import static java.lang.constant.ConstantDescs.CD_Object; 028 029public final record Constant<I>(I singleton) implements Constable, Factory<I> { 030 031 public Constant { 032 Objects.requireNonNull(singleton, "singleton"); 033 } 034 035 @Override // Factory<I> 036 public final I create(final Request<I> r) { 037 return this.singleton(); 038 } 039 040 @Override // Factory<I> 041 public final boolean destroys() { 042 return this.singleton() instanceof AutoCloseable; 043 } 044 045 // Experimental 046 @Override // Factory<I> 047 public final void destroy(final I i, final Request<I> request) { 048 Factory.super.destroy(i, request); 049 } 050 051 @Override // Constable 052 public final Optional<DynamicConstantDesc<I>> describeConstable() { 053 return Constables.describeConstable(this.singleton()) 054 .map(iDesc -> DynamicConstantDesc.of(BSM_INVOKE, 055 MethodHandleDesc.ofConstructor(ClassDesc.of(this.getClass().getName()), 056 CD_Object), 057 iDesc)); 058 } 059 060 061}