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 */ 017package org.apache.commons.compress.harmony.unpack200.bytecode; 018 019import java.io.DataOutputStream; 020import java.io.IOException; 021import java.util.Objects; 022 023import org.apache.commons.compress.utils.CharsetNames; 024 025/** 026 * UTF8 constant pool entry, used for storing long Strings. 027 */ 028public class CPUTF8 extends ConstantPoolEntry { 029 030 private final String utf8; 031 032 private boolean hashCodeComputed; 033 034 private int cachedHashCode; 035 036 public CPUTF8(final String string) { 037 this(string, -1); 038 } 039 040 /** 041 * Creates a new CPUTF8 instance 042 * 043 * @param utf8 TODO 044 * @param globalIndex - index in CpBands 045 * @throws NullPointerException if utf8 is null 046 */ 047 public CPUTF8(final String utf8, final int globalIndex) { 048 super(ConstantPoolEntry.CP_UTF8, globalIndex); 049 this.utf8 = Objects.requireNonNull(utf8, "utf8"); 050 } 051 052 @Override 053 public boolean equals(final Object obj) { 054 if (this == obj) { 055 return true; 056 } 057 if (obj == null) { 058 return false; 059 } 060 if (this.getClass() != obj.getClass()) { 061 return false; 062 } 063 final CPUTF8 other = (CPUTF8) obj; 064 return utf8.equals(other.utf8); 065 } 066 067 private void generateHashCode() { 068 hashCodeComputed = true; 069 final int PRIME = 31; 070 cachedHashCode = PRIME + utf8.hashCode(); 071 } 072 073 @Override 074 public int hashCode() { 075 if (!hashCodeComputed) { 076 generateHashCode(); 077 } 078 return cachedHashCode; 079 } 080 081 public void setGlobalIndex(final int index) { 082 globalIndex = index; 083 } 084 085 @Override 086 public String toString() { 087 return CharsetNames.UTF_8 + ":" + utf8; 088 } 089 090 public String underlyingString() { 091 return utf8; 092 } 093 094 @Override 095 protected void writeBody(final DataOutputStream dos) throws IOException { 096 dos.writeUTF(utf8); 097 } 098}