001 /** 002 Licensed to the Apache Software Foundation (ASF) under one or more 003 contributor license agreements. See the NOTICE file distributed with 004 this work for additional information regarding copyright ownership. 005 The ASF licenses this file to You under the Apache License, Version 2.0 006 (the "License"); you may not use this file except in compliance with 007 the License. You may obtain a copy of the License at 008 009 http://www.apache.org/licenses/LICENSE-2.0 010 011 Unless required by applicable law or agreed to in writing, software 012 distributed under the License is distributed on an "AS IS" BASIS, 013 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 See the License for the specific language governing permissions and 015 limitations under the License. 016 */ 017 package org.apache.commons.inject.api; 018 019 import java.lang.annotation.Annotation; 020 import java.lang.reflect.Array; 021 022 public class Key<T> implements IKey<T> { 023 public static final String NO_NAME = ""; 024 public static final Annotation[] NO_ANNOTATIONS = (Annotation[]) Array.newInstance(Annotation.class, 0); 025 private final Class<T> type; 026 private final String name; 027 private final Annotation[] annotations; 028 029 public Key(Class<T> pType, String pName, Annotation[] pAnnotations) { 030 if (pType == null) { 031 throw new NullPointerException("The keys type must not be null."); 032 } 033 this.type = pType; 034 if (pName == null) { 035 name = NO_NAME; 036 } else { 037 name = pName; 038 } 039 if (pAnnotations == null) { 040 annotations = NO_ANNOTATIONS; 041 } else { 042 annotations = pAnnotations; 043 } 044 } 045 046 public Key(Class<T> pType, String pName) { 047 this(pType, pName, NO_ANNOTATIONS); 048 } 049 050 public Key(Class<T> pType) { 051 this(pType, NO_NAME, NO_ANNOTATIONS); 052 } 053 054 @Override 055 public Class<T> getType() { 056 return type; 057 } 058 059 @Override 060 public String getName() { 061 return name; 062 } 063 064 @Override 065 public Annotation[] getAnnotations() { 066 return annotations; 067 } 068 069 @Override 070 public String toString() { 071 return toString(this); 072 } 073 074 public static String toString(IKey<?> pKey) { 075 final StringBuilder sb = new StringBuilder(); 076 sb.append("Type="); 077 sb.append(pKey.getType().getName()); 078 final String name = pKey.getName(); 079 if (name.length() > 0) { 080 sb.append(", Name="); 081 sb.append(name); 082 } 083 final Annotation[] annotations = pKey.getAnnotations(); 084 if (annotations.length > 0) { 085 sb.append(", Annotations=["); 086 for (int i = 0; i < annotations.length; i++) { 087 if (i > 0) { 088 sb.append(","); 089 } 090 sb.append(annotations[i]); 091 } 092 sb.append("]"); 093 } 094 return sb.toString(); 095 } 096 }