001/* 002 * The contents of this file are subject to the terms of the Common Development and 003 * Distribution License (the License). You may not use this file except in compliance with the 004 * License. 005 * 006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the 007 * specific language governing permission and limitations under the License. 008 * 009 * When distributing Covered Software, include this CDDL Header Notice in each file and include 010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL 011 * Header, with the fields enclosed by brackets [] replaced by your own identifying 012 * information: "Portions copyright [year] [name of copyright owner]". 013 * 014 * Copyright 2014-2015 ForgeRock AS. 015 */ 016 017package org.forgerock.util; 018 019/** 020 * A configuration option whose value can be stored in a set of {@link Options}. 021 * Refer to the appropriate class for the list of supported options. 022 * 023 * @param <T> 024 * The type of value associated with the option. 025 */ 026public final class Option<T> { 027 /** 028 * Defines an option with the provided type and default value. 029 * 030 * @param <T> 031 * The type of value associated with the option. 032 * @param type 033 * The type of value associated with the option. 034 * @param defaultValue 035 * The default value for the option. 036 * @return An option with the provided type and default value. 037 */ 038 public static <T> Option<T> of(final Class<T> type, final T defaultValue) { 039 return new Option<>(type, defaultValue); 040 } 041 042 /** 043 * Defines a boolean option with the provided default value. 044 * 045 * @param <T> 046 * The type of value associated with the option. 047 * @param defaultValue 048 * The default value for the option. 049 * @return A boolean option with the provided default value. 050 */ 051 @SuppressWarnings("unchecked") 052 public static <T> Option<T> withDefault(final T defaultValue) { 053 return new Option<>((Class<T>) defaultValue.getClass(), defaultValue); 054 } 055 056 private final T defaultValue; 057 private final Class<T> type; 058 059 private Option(final Class<T> type, final T defaultValue) { 060 this.type = type; 061 this.defaultValue = defaultValue; 062 } 063 064 T getValue(final Object value) { 065 return value != null ? type.cast(value) : defaultValue; 066 } 067}