001/* 002 * Copyright (C) 2009-2011 Mathias Doenitz 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 org.parboiled.common; 018 019/** 020 * A simple container holding a reference to another object. 021 * 022 * @param <T> 023 */ 024public class Reference<T> { 025 026 private T value; 027 028 /** 029 * Create a new Reference with a null value. 030 */ 031 public Reference() { 032 } 033 034 /** 035 * Create a new Reference to the given value object. 036 * 037 * @param value the value object 038 */ 039 public Reference(T value) { 040 this.value = value; 041 } 042 043 /** 044 * Sets this references value field to null. 045 * 046 * @return true 047 */ 048 public boolean clear() { 049 return set(null); 050 } 051 052 /** 053 * Sets this references value object to the given instance. 054 * 055 * @param value the value 056 * @return true 057 */ 058 public boolean set(T value) { 059 this.value = value; 060 return true; 061 } 062 063 /** 064 * Retrieves this references value object. 065 * 066 * @return the target 067 */ 068 public T get() { 069 return value; 070 } 071 072 /** 073 * Retrieves this references value field and clears it. 074 * Equivalent to getAndSet(null). 075 * 076 * @return the target 077 */ 078 public T getAndClear() { 079 return getAndSet(null); 080 } 081 082 /** 083 * Replaces this references value with the given one. 084 * 085 * @param value the new value 086 * @return the previous value 087 */ 088 public T getAndSet(T value) { 089 T t = this.value; 090 this.value = value; 091 return t; 092 } 093 094 /** 095 * Replaces this references value with the given one. 096 * 097 * @param value the new value 098 * @return the new value 099 */ 100 public T setAndGet(T value) { 101 return this.value = value; 102 } 103 104 /** 105 * @return true if this Reference holds a non-null value 106 */ 107 public boolean isSet() { 108 return value != null; 109 } 110 111 /** 112 * @return true if this Reference holds a null value 113 */ 114 public boolean isNotSet() { 115 return value == null; 116 } 117}