diff options
author | doko <doko@138bc75d-0d04-0410-961f-82ee72b054a4> | 2008-10-21 17:55:01 +0000 |
---|---|---|
committer | doko <doko@138bc75d-0d04-0410-961f-82ee72b054a4> | 2008-10-21 17:55:01 +0000 |
commit | 2bc043354c4edb1f5aad751285060fb722a63ea1 (patch) | |
tree | 6de8da5758622565799768e49cd0de6698ca3cb8 /libjava/classpath/java/lang | |
parent | be9f921eb27de7f5f22e4755df15340ab8042a09 (diff) | |
download | gcc-2bc043354c4edb1f5aad751285060fb722a63ea1.tar.gz |
libjava/ChangeLog:
2008-10-21 Andrew John Hughes <gnu_andrew@member.fsf.org>
* sources.am, Makfile.in: Regenerate.
2008-10-17 Matthias Klose <doko@ubuntu.com>
* configure.ac: Fix bashisms.
* configure: Regenerate.
2008-10-15 Matthias Klose <doko@ubuntu.com>
* configure.ac: Disable build of gjdoc, if configured without
--with-antlr-jar or if no antlr.jar found.
* configure: Regenerate.
2008-10-09 Andrew John Hughes <gnu_andrew@member.fsf.org>
* classpath/configure.ac,
* classpath/m4/ac_prog_antlr.m4,
* classpath/m4/ac_prog_java.m4,
* classpath/tools/Makefile.am:
Ported --regen-gjdoc-parser patch and
cantlr support from GNU Classpath.
2008-10-06 Andrew Haley <aph@redhat.com>
* java/lang/Thread.java (Thread): Always create the ThreadLocalMap
when creating a thread.
(getThreadLocals) Don't lazily create the ThreadLocalMap.
2008-09-28 Andrew John Hughes <gnu_andrew@member.fsf.org>
* classpath/java/lang/ThreadLocalMap.java,
* java/lang/ThreadLocalMap$Entry.h,
* java/lang/ThreadLocalMap.h,
* lib/java/lang/ThreadLocalMap.class,
* lib/java/lang/ThreadLocalMap$Entry.class:
Add the new files for the ThreadLocal patch.
2008-09-28 Andrew John Hughes <gnu_andrew@member.fsf.org>
* classpath/ChangeLog,
* classpath/java/lang/InheritableThreadLocal.java,
* classpath/java/lang/Thread.java,
* classpath/java/lang/ThreadLocal.java:
Merge Daniel Frampton's ThreadLocal patch.
* gcj/javaprims.h: Updated.
* java/lang/Thread.h: Regenerated.
* java/lang/Thread.java:
Replace WeakIdentityHashMap with ThreadLocalMap.
(getThreadLocals()): Likewise.
* java/lang/ThreadLocal.h: Regenerated.
* java/lang/ThreadLocal.java:
(computeNextHash()): New method.
(ThreadLocal()): Initialise fastHash.
(internalGet()): Updated to match Classpath's get().
(internalSet(Object)): Likewise for set(Object).
(internalRemove()): Likewise for remove().
2008-09-25 Andrew John Hughes <gnu_andrew@member.fsf.org>
* classpath/configure,
* classpath/configure.ac:
Resynchronise with Classpath's configure.
* classpath/examples/Makefile.in:
Add equivalent support for building as in
tools/Makefile.in.
* classpath/java/nio/Buffer.java,
* classpath/java/nio/ByteBuffer.java,
* classpath/java/nio/ByteBufferImpl.java,
* classpath/java/nio/CharBuffer.java,
* classpath/java/nio/CharBufferImpl.java,
* classpath/java/nio/CharSequenceBuffer.java,
* classpath/java/nio/CharViewBufferImpl.java,
* classpath/java/nio/DirectByteBufferImpl.java,
* classpath/java/nio/DoubleBuffer.java,
* classpath/java/nio/DoubleBufferImpl.java,
* classpath/java/nio/DoubleViewBufferImpl.java,
* classpath/java/nio/FloatBuffer.java,
* classpath/java/nio/FloatBufferImpl.java,
* classpath/java/nio/FloatViewBufferImpl.java,
* classpath/java/nio/IntBuffer.java,
* classpath/java/nio/IntBufferImpl.java,
* classpath/java/nio/IntViewBufferImpl.java,
* classpath/java/nio/LongBuffer.java,
* classpath/java/nio/LongBufferImpl.java,
* classpath/java/nio/LongViewBufferImpl.java,
* classpath/java/nio/MappedByteBuffer.java,
* classpath/java/nio/MappedByteBufferImpl.java,
* classpath/java/nio/ShortBuffer.java,
* classpath/java/nio/ShortBufferImpl.java,
* classpath/java/nio/ShortViewBufferImpl.java:
Replace use of gnu.classpath.Pointer with gnu.gcj.RawData,
and fix some formatting issues.
* classpath/tools/gnu/classpath/tools/gjdoc/expr/JavaLexer.java,
* classpath/tools/gnu/classpath/tools/gjdoc/expr/JavaLexer.smap,
* classpath/tools/gnu/classpath/tools/gjdoc/expr/JavaRecognizer.java,
* classpath/tools/gnu/classpath/tools/gjdoc/expr/JavaRecognizer.smap,
* classpath/tools/gnu/classpath/tools/gjdoc/expr/JavaTokenTypes.java,
* classpath/tools/gnu/classpath/tools/gjdoc/expr/JavaTokenTypes.txt:
Regenerated (later version of antlr).
* java/nio/Buffer.h: Regenerated.
* java/nio/Buffer.java: Ported changes from Classpath.
* java/nio/ByteBuffer.h,
* java/nio/CharBuffer.h: Regenerated.
* java/nio/DirectByteBufferImpl.java: Ported changes from
Classpath.
* java/nio/DoubleBuffer.h,
* java/nio/FloatBuffer.h,
* java/nio/IntBuffer.h,
* java/nio/LongBuffer.h,
* java/nio/MappedByteBuffer.h,
* java/nio/MappedByteBufferImpl.h: Regenerated.
* java/nio/MappedByteBufferImpl.java: Ported changes from
Classpath.
* java/nio/ShortBuffer.h: Regenerated.
2008-09-24 Matthias Klose <doko@ubuntu.com>
* configure.ac: Search for antlr.jar, if not configured.
* configure: Regenerate.
2008-09-24 Matthias Klose <doko@ubuntu.com>
* Makefile.am: Build a gjdoc binary, if enabled.
* configure.ac: Add options --disable-gjdoc, --with-antlr-jar=file.
* Makefile.in, */Makefile.in, configure: Regenerate.
2008-09-22 Andrew Haley <aph@redhat.com>
* java/lang/String.java (toString(char[], int, int)): New method.
2008-09-14 Matthias Klose <doko@ubuntu.com>
Import GNU Classpath (libgcj-import-20080914).
* Regenerate class and header files.
* Regenerate auto* files.
* configure.ac: Don't pass --disable-gjdoc to classpath.
* sources.am: Regenerated.
* HACKING: Mention to build gjdoc in maintainer builds.
* gnu/classpath/Configuration.java: Update classpath version.
* gcj/javaprims.h: Update.
2008-09-08 Andrew John Hughes <gnu_andrew@member.fsf.org>
* Makefile.am: Replace natStringBuffer.cc
and natStringBuilder.cc with natAbstractStringBuffer.cc.
* Makefile.in: Regenerated.
* java/lang/AbstractStringBuffer.java:
(append(int)): Made native.
(regionMatches(int,String)): Likewise.
* java/lang/StringBuffer.h: Regenerated.
* java/lang/StringBuffer.java: Remerged with GNU Classpath.
* java/lang/StringBuilder.h: Regenerated.
* java/lang/StringBuilder.java: Remerged with GNU Classpath.
* java/lang/natAbstractStringBuffer.cc: Provide common
native methods for StringBuffer and StringBuilder.
* java/lang/natStringBuffer.cc,
* java/lang/natStringBuilder.cc: Removed.
2008-09-04 Andrew John Hughes <gnu_andrew@member.fsf.org>
* Makefile.in,
* classpath/configure: Regenerated.
* gnu/gcj/util/natDebug.cc,
* gnu/gcj/xlib/natColormap.cc,
* gnu/gcj/xlib/natDisplay.cc,
* gnu/gcj/xlib/natDrawable.cc,
* gnu/gcj/xlib/natFont.cc,
* gnu/gcj/xlib/natWMSizeHints.cc,
* gnu/gcj/xlib/natWindow.cc,
* gnu/gcj/xlib/natXImage.cc:
Add :: prefix to namespaces.
* java/io/CharArrayWriter.h,
* java/lang/StringBuffer.h:
Regenerated using patched gjavah.
* java/lang/natStringBuffer.cc:
Fix naming of append(jint).
* java/sql/Timestamp.h: Regenerated
using patched gjavah.
* jni.cc: Rename p to functions
to match change in GNU Classpath.
* scripts/makemake.tcl: Switch
gnu.java.math to BC compilation.
* sources.am: Regenerated.
2008-08-21 Andrew John Hughes <gnu_andrew@member.fsf.org>
* Makefile.in: Updated location of Configuration.java.
* classpath/lib/gnu/java/locale/LocaleData.class: Regenerated.
2008-08-18 Andrew John Hughes <gnu_andrew@member.fsf.org>
* Makefile.in: Updated with new Java files.
* classpath/configure: Regenerated.
* classpath/tools/Makefile.am: Add missing
use of GJDOC_EX so --disable-gjdoc works.
* classpath/tools/Makefile.in: Regenerated.
2008-08-15 Matthias Klose <doko@ubuntu.com>
Import GNU Classpath (libgcj-import-20080811).
* Regenerate class and header files.
* Regenerate auto* files.
* configure.ac: Don't pass --with-fastjar to classpath, substitute new
dummy value in classpath/gnu/classpath/Configuration.java.in, pass
--disable-gjdoc to classpath.
* scripts/makemake.tcl:
* sources.am: Regenerated.
* java/lang/AbstractStringBuffer.java, gnu/java/lang/VMCPStringBuilder.java:
New, copied from classpath, use System instead of VMSystem.
* java/lang/StringBuffer.java: Merge from classpath.
* java/lang/ClassLoader.java: Merge from classpath.
* gcj/javaprims.h: Update class definitions,
remove _Jv_jobjectRefType, jobjectRefType definitions.
libjava/classpath/ChangeLog.gcj:
2008-10-21 Matthias Klose <doko@ubuntu.com>
* classpath/tools/gnu/classpath/tools/gjdoc/expr/Java*: Move from ...
* classpath/tools/generated/gnu/classpath/tools/gjdoc/expr/ ... here.
* Update .class files.
2008-10-21 Andrew John Hughes <gnu_andrew@member.fsf.org>
* tools/Makefile.am:
Always generate parser in the srcdir.
2008-10-21 Matthias Klose <doko@ubuntu.com>
* doc/Makefile.am (MAINTAINERCLEANFILES): Add gjdoc.1.
* doc/Makefile.in: Regenerate.
2008-10-20 Matthias Klose <doko@ubuntu.com>
* configure.ac: Don't check for working java, if not configured
with --enable-java-maintainer-mode.
* configure: Regenerate.
2008-10-19 Matthias Klose <doko@ubuntu.com>
* m4/ac_prog_java.m4: Revert previous change.
* m4/ac_prog_javac.m4: Apply it here.
* configure: Regenerate.
2008-10-19 Matthias Klose <doko@ubuntu.com>
* m4/ac_prog_javac.m4: Don't check for working javac, if not configured
with --enable-java-maintainer-mode.
* configure: Regenerate.
* Makefile.in, */Makefile.in: Regenerate.
2008-09-30 Matthias Klose <doko@ubuntu.com>
* m4/ac_prog_antlr.m4: Check for cantlr binary as well.
2008-09-29 Matthias Klose <doko@ubuntu.com>
* m4/ac_prog_antlr.m4: Check for antlr binary as well.
2008-09-28 Matthias Klose <doko@ubuntu.com>
* PR libgcj/37636. Revert:
2008-02-20 Matthias Klose <doko@ubuntu.com>
* tools/Makefile.am ($(TOOLS_ZIP)): Revert part of previous change,
Do copy resource files in JAVA_MAINTAINER_MODE only.
* tools/Makefile.in: Regenerate.
2008-09-14 Matthias Klose <doko@ubuntu.com>
* m4/ac_prog_javac_works.m4, m4/ac_prog_javac.m4, m4/acinclude.m4:
Revert local changes.
* m4/ac_prog_antlr.m4: Check for an runantlr binary.
* tools/Makefile.am, lib/Makefile.am: Revert local changes (JCOMPILER).
* tools/Makefile.am: Remove USE_JAVAC_FLAGS, pass ANTLR_JAR in
GLIBJ_CLASSPATH.
2008-09-14 Matthias Klose <doko@ubuntu.com>
Revert:
Daniel Frampton <zyridium at zyridium.net>
* AUTHORS: Added.
* java/lang/InheritableThreadLocal.java,
* java/lang/Thread.java,
* java/lang/ThreadLocal.java:
Modified to use java.lang.ThreadLocalMap.
* java/lang/ThreadLocalMap.java:
New cheaper ThreadLocal-specific WeakHashMap.
2008-08-15 Matthias Klose <doko@ubuntu.com>
* m4/acinclude.m4 (CLASSPATH_JAVAC_MEM_CHECK): Remove unknown
args for javac.
libjava/classpath/ChangeLog:
2008-10-20 Andrew John Hughes <gnu_andrew@member.fsf.org>
* m4/ac_prog_antlr.m4:
Remove redundant checks.
* tools/Makefile.am:
Use gjdoc_gendir when calling antlr.
2008-10-15 Andrew John Hughes <gnu_andrew@member.fsf.org>
* configure.ac:
Remove superfluous AC_PROG_JAVA call.
2008-10-06 Andrew John Hughes <gnu_andrew@member.fsf.org>
* m4/ac_prog_antlr:
Check for cantlr as well.
* tools/Makefile.am:
Only build GJDoc parser when both
CREATE_GJDOC and CREATE_GJDOC_PARSER
are on.
2008-10-02 Andrew John Hughes <gnu_andrew@member.fsf.org>
* configure.ac:
Add regen-gjdoc-parser option,
and separate antlr tests.
* m4/ac_prog_antlr.m4:
Turn single test into AC_LIB_ANTLR
and AC_PROG_ANTLR.
* m4/ac_prog_java.m4:
Quote tests.
* tools/Makefile.am:
Support CREATE_GJDOC_PARSER option.
2008-09-14 Andrew John Hughes <gnu_andrew@member.fsf.org>
* examples/Makefile.am:
Check lib directly as well as glibj.zip
for boot classes.
* m4/acinclude.m4:
Only require the class files to be built
to allow the tools and examples to be built,
not the installation of glibj.zip.
* tools/Makefile.am:
Check lib directly as well as glibj.zip
for boot classes.
2008-09-13 Andrew John Hughes <gnu_andrew@member.fsf.org>
* examples/Makefile.am,
* lib/Makefile.am:
Add GCJ rules.
* m4/ac_prog_javac.m4:
Check whether JAVAC is gcj.
* m4/ac_prog_javac_works.m4:
Add GCJ rules.
* m4/acinclude.m4:
Don't bother checking for -J
if using GCJ.
* tools/Makefile.am:
Add GCJ rules.
2007-08-23 Daniel Frampton <zyridium@zyridium.net>
* AUTHORS: Added.
* java/lang/InheritableThreadLocal.java,
* java/lang/Thread.java,
* java/lang/ThreadLocal.java:
Modified to use java.lang.ThreadLocalMap.
* java/lang/ThreadLocalMap.java:
New cheaper ThreadLocal-specific WeakHashMap.
2008-02-07 Ian Rogers <ian.rogers@manchester.ac.uk>
* java/util/zip/ZipEntry.java:
Use byte fields instead of integer fields,
store the time as well as the DOS time and
don't retain a global Calendar instance.
(setDOSTime(int)): Set KNOWN_DOSTIME instead
of KNOWN_TIME, and unset KNOWN_TIME.
(getDOSTime()): Compute DOS time from UNIX time
only when needed.
(clone()): Provide cloning via the ZipEntry constructor
where possible.
(setTime(long)): Don't compute DOS time at this point.
(getCalendar()): Removed.
2008-09-09 Andrew John Hughes <gnu_andrew@member.fsf.org>
* tools/gnu/classpath/tools/getopt/Parser.java:
(setHeader(String)): Make synchronized.
(setFooter(String)): Likewise.
* tools/gnu/classpath/tools/rmic/SourceGiopRmicCompiler.java,
(reset()): Make synchronized.
(name(Class)): Likewise.
2008-09-04 Robert Schuster <robertschuster@fsfe.org>
* gnu/java/nio/charset/ByteDecodeLoopHelper:
(arrayDecodeLoop): Added new break label, escape to that label.
* gnu/java/nio/charset/ByteEncodeLoopHelper:
(arrayDecodeLoop): Added new break label, escape to that label.
2008-09-04 Robert Schuster <robertschuster@fsfe.org>
* java/text/DecimalFormat.java:
(scanFix): Use 'i + 1' when looking at following character.
(scanNegativePattern): Dito.
2008-09-02 Andrew John Hughes <gnu_andrew@member.fsf.org>
* tools/gnu/classpath/tools/javah/ClassWrapper.java:
(makeVtable()): Populate methodNameMap.
(printMethods(CniPrintStream)): Always use pre-populated
methodNameMap for bridge targets.
2008-09-01 Mario Torre <neugens@aicas.com>
* gnu/java/awt/peer/x/XImage.java (XImageProducer): remove @Override
annotation to allow compilation on javac < 1.6 and ecj < 3.4.
2008-09-01 Mario Torre <neugens@aicas.com>
* gnu/java/awt/peer/x/XGraphicsDevice.java (getDisplay): fix to support
new Escher API.
* gnu/java/awt/peer/x/XImage.java (getSource): method implemented.
* gnu/java/awt/peer/x/XImage.java (XImageProducer): implement ImageProducer
for getSource.
2008-09-01 Andrew John Hughes <gnu_andrew@member.fsf.org>
* gnu/java/util/regex/BacktrackStack.java,
* gnu/java/util/regex/CharIndexed.java,
* gnu/java/util/regex/CharIndexedCharArray.java,
* gnu/java/util/regex/CharIndexedCharSequence.java,
* gnu/java/util/regex/CharIndexedInputStream.java,
* gnu/java/util/regex/CharIndexedString.java,
* gnu/java/util/regex/CharIndexedStringBuffer.java,
* gnu/java/util/regex/RE.java,
* gnu/java/util/regex/REException.java,
* gnu/java/util/regex/REFilterInputStream.java,
* gnu/java/util/regex/REMatch.java,
* gnu/java/util/regex/REMatchEnumeration.java,
* gnu/java/util/regex/RESyntax.java,
* gnu/java/util/regex/REToken.java,
* gnu/java/util/regex/RETokenAny.java,
* gnu/java/util/regex/RETokenBackRef.java,
* gnu/java/util/regex/RETokenChar.java,
* gnu/java/util/regex/RETokenEnd.java,
* gnu/java/util/regex/RETokenEndOfPreviousMatch.java,
* gnu/java/util/regex/RETokenEndSub.java,
* gnu/java/util/regex/RETokenIndependent.java,
* gnu/java/util/regex/RETokenLookAhead.java,
* gnu/java/util/regex/RETokenLookBehind.java,
* gnu/java/util/regex/RETokenNamedProperty.java,
* gnu/java/util/regex/RETokenOneOf.java,
* gnu/java/util/regex/RETokenPOSIX.java,
* gnu/java/util/regex/RETokenRange.java,
* gnu/java/util/regex/RETokenRepeated.java,
* gnu/java/util/regex/RETokenStart.java,
* gnu/java/util/regex/RETokenWordBoundary.java,
* gnu/java/util/regex/UncheckedRE.java:
Fix indentation.
2008-09-01 Andrew John Hughes <gnu_andrew@member.fsf.org>
* gnu/java/util/regex/RETokenStart.java:
(getMaximumLength()): Add Override annotation.
(matchThis(CharIndexed, REMatch)): Likewise.
(returnsFixedLengthMatches()): Renamed from
returnsFixedLengthmatches and added Override
annotation.
(findFixedLengthMatches(CharIndexed,REMatch,int)):
Add Override annotation.
(dump(CPStringBuilder)): Likewise.
* gnu/javax/print/ipp/IppRequest.java:
(RequestWriter.writeOperationAttributes(AttributeSet)):
Throw exception, don't just create and drop it.
* javax/management/MBeanServerPermission.java:
(MBeanServerPermissionCollection.add(Permission)): Compare
against individual Strings not the entire array, and
store the result of replace.
* javax/swing/text/html/StyleSheet.java:
(setBaseFontSize(size)): Store result of trim().
2008-09-01 Andrew John Hughes <gnu_andrew@member.fsf.org>
* javax/tools/FileObject.java:
(openReader(boolean)): Document new parameter.
2008-03-27 Michael Franz <mvfranz@gmail.com>
PR classpath/35690:
* javax/tools/FileObject.java:
(toUri()): Fix case from toURI.
(openReader(boolean)): Add missing boolean argument.
2008-08-26 Andrew John Hughes <gnu_andrew@member.fsf.org>
PR classpath/35487:
* gnu/javax/management/Server.java:
(beans): Change to ConcurrentHashMap.
(defaultDomain): Make final.
(outer): Likewise.
(LazyListenersHolder): Added to wrap
listeners, also now a ConcurrentHashMap,
providing lazy initialisation safely.
(sequenceNumber): Documented.
(getBean(ObjectName)): Remove redundant cast.
(addNotificationListener(ObjectName,NotificationListener,
NotificationFilter,Object)): Remove map initialisation
and use holder.
(getObjectInstance(ObjectName)): Remove redundant cast.
(registerMBean(Object,ObjectName)): Add bean atomically.
(removeNotificationListener(ObjectName,NotificationListener)):
Simplified.
(removeNotificationListener(ObjectName,NotificationListener,
NotificationFilter,Object)): Likewise.
(notify(ObjectName,String)): Documented.
2008-08-26 Andrew John Hughes <gnu_andrew@member.fsf.org>
* gnu/javax/management/Server.java:
Genericised.
2008-08-26 Andrew John Hughes <gnu_andrew@member.fsf.org>
* gnu/javax/management/Translator.java:
Genericised.
2008-08-26 Andrew John Hughes <gnu_andrew@member.fsf.org>
* javax/management/DefaultLoaderRepository.java,
* javax/management/JMX.java,
* javax/management/MBeanAttributeInfo.java,
* javax/management/MBeanConstructorInfo.java,
* javax/management/MBeanOperationInfo.java,
* javax/management/MBeanServerDelegate.java:
Fix warnings due to generics.
2008-08-25 Andrew John Hughes <gnu_andrew@member.fsf.org>
* javax/management/MBeanPermission.java,
* javax/management/MBeanServerDelegate.java,
* javax/management/MBeanServerFactory.java,
* javax/management/MBeanServerInvocationHandler.java,
* javax/management/MBeanServerPermission.java:
Fix warnings due to use of non-generic collections.
2008-08-25 Mario Torre <neugens@aicas.com>
* gnu/javax/rmi/CORBA/RmiUtilities.java (readValue): check if sender is
null to avoid NPE.
2008-08-22 Mario Torre <neugens@aicas.com>
* gnu/CORBA/OrbFunctional.java (set_parameters): Fix
NullPointerException checking when param is null.
2008-08-23 Andrew John Hughes <gnu_andrew@member.fsf.org>
* java/util/regex/Matcher.java:
(reset()): Reset append position so
we don't try and append to the end of
the old input.
2008-08-22 Andrew John Hughes <gnu_andrew@member.fsf.org>
PR classpath/32028:
* m4/acinclude.m4:
Also allow versions of GJDoc from 0.8* on, as
CVS is 0.8.0-pre.
2008-08-21 Andrew John Hughes <gnu_andrew@member.fsf.org>
PR classpath/32028:
* m4/acinclude.m4:
(CLASSPATH_WITH_GJDOC): Ensure version 0.7.9 is
being used.
2008-08-20 Andrew John Hughes <gnu_andrew@member.fsf.org>
* tools/Makefile.am:
Add taglets subdirectory to list of excluded
paths when GJDoc is not compiled.
2008-08-19 David P Grove <groved@us.ibm.com>
* scripts/check_jni_methods.sh.in:
Fix build issue on AIX by splitting generation
of method list.
2008-08-18 Andrew John Hughes <gnu_andrew@member.fsf.org>
* native/jni/gstreamer-peer/gst_native_pipeline.c:
(get_free_space(int)): Use #else not #elif when
there is no condition.
2008-08-17 Andrew John Hughes <gnu_andrew@member.fsf.org>
PR classpath/31895:
* java/text/DecimalFormat.java:
(setCurrency(Currency)): Update prefixes and
suffixes when currency changes.
* java/text/DecimalFormatSymbols.java:
(DecimalFormatSymbols(Locale)): Set locale earlier
so it can be used by setCurrency(Currency).
(setCurrency(Currency)): Set the symbol correctly using
the locale of the instance.
* java/util/Currency.java:
Throw error instead of just printing a message.
2008-08-17 Andrew John Hughes <gnu_andrew@member.fsf.org>
* javax/activation/ActivationDataFlavor.java:
Suppress warnings from public API.
(mimeType): Made final.
(representationClass): Added generic type and
made final.
(normalizeMimeTypeParameter(String,String)):
Use CPStringBuilder.
* javax/activation/CommandInfo.java:
(verb): Made final.
(className): Made final.
* javax/activation/DataHandler.java:
(dataSource): Made final.
* javax/activation/FileDataSource.java:
(file): Made final.
* javax/activation/MailcapCommandMap.java:
Use generics on collections and CPStringBuilder
instead of StringBuffer.
* javax/activation/MimeType.java:
(toString()): Use CPStringBuilder.
(getBaseType()): Likewise.
* javax/activation/MimeTypeParameterList.java:
Use generics on collections and CPStringBuilder
instead of StringBuffer.
* javax/activation/MimeTypeParseException.java:
(MimeTypeParseException(String,String)): Use
CPStringBuilder.
* javax/activation/MimetypesFileTypeMap.java:
Use generics on collections and CPStringBuilder
instead of StringBuffer.
* javax/activation/URLDataSource.java:
(url): Made final.
2008-08-17 Andrew John Hughes <gnu_andrew@member.fsf.org>
* gnu/javax/activation/viewers/ImageViewer.java,
* gnu/javax/activation/viewers/TextEditor.java,
* gnu/javax/activation/viewers/TextViewer.java,
* javax/activation/ActivationDataFlavor.java,
* javax/activation/CommandInfo.java,
* javax/activation/CommandMap.java,
* javax/activation/CommandObject.java,
* javax/activation/DataContentHandler.java,
* javax/activation/DataContentHandlerFactory.java,
* javax/activation/DataHandler.java,
* javax/activation/DataHandlerDataSource.java,
* javax/activation/DataSource.java,
* javax/activation/DataSourceDataContentHandler.java,
* javax/activation/FileDataSource.java,
* javax/activation/FileTypeMap.java,
* javax/activation/MailcapCommandMap.java,
* javax/activation/MimeType.java,
* javax/activation/MimeTypeParameterList.java,
* javax/activation/MimeTypeParseException.java,
* javax/activation/MimetypesFileTypeMap.java,
* javax/activation/ObjectDataContentHandler.java,
* javax/activation/URLDataSource.java,
* javax/activation/UnsupportedDataTypeException.java,
* javax/activation/package.html,
* resource/META-INF/mailcap.default,
* resource/META-INF/mimetypes.default:
Import GNU JAF CVS as of 17/08/2008.
2006-04-25 Archit Shah <ashah@redhat.com>
* javax/activation/MimeTypeParameterList.java:
Insert ';' separator before parameter list.
2005-06-29 Xavier Poinsard <xpoinsard@openpricer.com>
* javax/activation/ObjectDataContentHandler.java:
Fixed typo.
2005-05-28 Chris Burdess <dog@bluezoo.org>
* javax/activation/CommandMap.java,
* javax/activation/MailcapCommandMap.java:
Updated to JAF 1.1.
2004-06-09 Chris Burdess <dog@bluezoo.org>
* javax/activation/MailcapCommandMap.java:
Fixed bug whereby x-java prefix was not
attempted.
2008-08-17 Andrew John Hughes <gnu_andrew@member.fsf.org>
* AUTHORS: Added Laszlo.
2008-04-20 Andrew John Hughes <gnu_andrew@member.fsf.org>
PR classpath/30436:
* java/util/Scanner.java:
Fix package to be java.util and correct
indentation.
2007-07-25 Laszlo Andras Hernadi <e0327023@student.tuwien.ac.at>
PR classpath/30436:
* java/util/Scanner.java:
Initial implementation.
2008-08-17 Andrew John Hughes <gnu_andrew@member.fsf.org>
* java/util/regex/Matcher.java:
(toMatchResult()): Implemented.
2008-08-13 Joshua Sumali <jsumali@redhat.com>
* doc/Makefile.am (gjdoc.pod): Generate gjdoc pod from cp-tools.texinfo
instead of invoke.texi. Remove invoke.texi from EXTRA_DIST.
* doc/invoke.texi: Removed and merged into ...
* doc/cp-tools.texinfo: Here
2008-08-12 Robert Schuster <robertschuster@fsfe.org>
* native/jni/java-net/local.c
(local_bind): Removed fprintf call, fixed access outside
of array bounds.
git-svn-id: svn+ssh://gcc.gnu.org/svn/gcc/trunk@141271 138bc75d-0d04-0410-961f-82ee72b054a4
Diffstat (limited to 'libjava/classpath/java/lang')
24 files changed, 3618 insertions, 929 deletions
diff --git a/libjava/classpath/java/lang/AbstractStringBuffer.java b/libjava/classpath/java/lang/AbstractStringBuffer.java new file mode 100644 index 00000000000..dc3a8c9ecda --- /dev/null +++ b/libjava/classpath/java/lang/AbstractStringBuffer.java @@ -0,0 +1,1037 @@ +/* AbstractStringBuffer.java -- Growable strings + Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2008 + Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package java.lang; + +import java.io.Serializable; + +/** + * This class is based on gnu.classpath.ClasspathStringBuffer but + * is package-private to java.lang so it can be used as the basis + * for StringBuffer and StringBuilder. + * If you modify this, please consider also modifying that code. + */ +abstract class AbstractStringBuffer + implements Serializable, CharSequence, Appendable +{ + + /** + * Index of next available character (and thus the size of the current + * string contents). Note that this has permissions set this way so that + * String can get the value. + * + * @serial the number of characters in the buffer + */ + int count; + + /** + * The buffer. Note that this has permissions set this way so that String + * can get the value. + * + * @serial the buffer + */ + char[] value; + + /** + * The default capacity of a buffer. + */ + private static final int DEFAULT_CAPACITY = 16; + + /** + * Create a new AbstractStringBuffer with default capacity 16. + */ + AbstractStringBuffer() + { + this(DEFAULT_CAPACITY); + } + + /** + * Create an empty <code>StringBuffer</code> with the specified initial + * capacity. + * + * @param capacity the initial capacity + * @throws NegativeArraySizeException if capacity is negative + */ + AbstractStringBuffer(int capacity) + { + value = new char[capacity]; + } + + /** + * Create a new <code>StringBuffer</code> with the characters in the + * specified <code>String</code>. Initial capacity will be the size of the + * String plus 16. + * + * @param str the <code>String</code> to convert + * @throws NullPointerException if str is null + */ + AbstractStringBuffer(String str) + { + count = str.count; + value = new char[count + DEFAULT_CAPACITY]; + str.getChars(0, count, value, 0); + } + + /** + * Create a new <code>StringBuffer</code> with the characters in the + * specified <code>CharSequence</code>. Initial capacity will be the + * length of the sequence plus 16; if the sequence reports a length + * less than or equal to 0, then the initial capacity will be 16. + * + * @param seq the initializing <code>CharSequence</code> + * @throws NullPointerException if str is null + * @since 1.5 + */ + AbstractStringBuffer(CharSequence seq) + { + int len = seq.length(); + count = len <= 0 ? 0 : len; + value = new char[count + DEFAULT_CAPACITY]; + for (int i = 0; i < len; ++i) + value[i] = seq.charAt(i); + } + + /** + * Increase the capacity of this <code>StringBuffer</code>. This will + * ensure that an expensive growing operation will not occur until + * <code>minimumCapacity</code> is reached. The buffer is grown to the + * larger of <code>minimumCapacity</code> and + * <code>capacity() * 2 + 2</code>, if it is not already large enough. + * + * @param minimumCapacity the new capacity + * @see #capacity() + */ + public void ensureCapacity(int minimumCapacity) + { + ensureCapacity_unsynchronized(minimumCapacity); + } + + /** + * Set the length of this StringBuffer. If the new length is greater than + * the current length, all the new characters are set to '\0'. If the new + * length is less than the current length, the first <code>newLength</code> + * characters of the old array will be preserved, and the remaining + * characters are truncated. + * + * @param newLength the new length + * @throws IndexOutOfBoundsException if the new length is negative + * (while unspecified, this is a StringIndexOutOfBoundsException) + * @see #length() + */ + public void setLength(int newLength) + { + if (newLength < 0) + throw new StringIndexOutOfBoundsException(newLength); + + int valueLength = value.length; + + /* Always call ensureCapacity_unsynchronized in order to preserve + copy-on-write semantics. */ + ensureCapacity_unsynchronized(newLength); + + if (newLength < valueLength) + { + /* If the StringBuffer's value just grew, then we know that + value is newly allocated and the region between count and + newLength is filled with '\0'. */ + count = newLength; + } + else + { + /* The StringBuffer's value doesn't need to grow. However, + we should clear out any cruft that may exist. */ + while (count < newLength) + value[count++] = '\0'; + } + } + + /** + * Get the character at the specified index. + * + * @param index the index of the character to get, starting at 0 + * @return the character at the specified index + * @throws IndexOutOfBoundsException if index is negative or >= length() + * (while unspecified, this is a StringIndexOutOfBoundsException) + */ + public char charAt(int index) + { + if (index < 0 || index >= count) + throw new StringIndexOutOfBoundsException(index); + return value[index]; + } + + /** + * Get the code point at the specified index. This is like #charAt(int), + * but if the character is the start of a surrogate pair, and the + * following character completes the pair, then the corresponding + * supplementary code point is returned. + * @param index the index of the codepoint to get, starting at 0 + * @return the codepoint at the specified index + * @throws IndexOutOfBoundsException if index is negative or >= length() + * @since 1.5 + */ + public int codePointAt(int index) + { + return Character.codePointAt(value, index, count); + } + + /** + * Get the code point before the specified index. This is like + * #codePointAt(int), but checks the characters at <code>index-1</code> and + * <code>index-2</code> to see if they form a supplementary code point. + * @param index the index just past the codepoint to get, starting at 0 + * @return the codepoint at the specified index + * @throws IndexOutOfBoundsException if index is negative or >= length() + * @since 1.5 + */ + public int codePointBefore(int index) + { + // Character.codePointBefore() doesn't perform this check. We + // could use the CharSequence overload, but this is just as easy. + if (index >= count) + throw new IndexOutOfBoundsException(); + return Character.codePointBefore(value, index, 1); + } + + /** + * Get the specified array of characters. <code>srcOffset - srcEnd</code> + * characters will be copied into the array you pass in. + * + * @param srcOffset the index to start copying from (inclusive) + * @param srcEnd the index to stop copying from (exclusive) + * @param dst the array to copy into + * @param dstOffset the index to start copying into + * @throws NullPointerException if dst is null + * @throws IndexOutOfBoundsException if any source or target indices are + * out of range (while unspecified, source problems cause a + * StringIndexOutOfBoundsException, and dest problems cause an + * ArrayIndexOutOfBoundsException) + * @see System#arraycopy(Object, int, Object, int, int) + */ + public void getChars(int srcOffset, int srcEnd, + char[] dst, int dstOffset) + { + if (srcOffset < 0 || srcEnd > count || srcEnd < srcOffset) + throw new StringIndexOutOfBoundsException(); + VMSystem.arraycopy(value, srcOffset, dst, dstOffset, srcEnd - srcOffset); + } + + /** + * Set the character at the specified index. + * + * @param index the index of the character to set starting at 0 + * @param ch the value to set that character to + * @throws IndexOutOfBoundsException if index is negative or >= length() + * (while unspecified, this is a StringIndexOutOfBoundsException) + */ + public void setCharAt(int index, char ch) + { + if (index < 0 || index >= count) + throw new StringIndexOutOfBoundsException(index); + // Call ensureCapacity to enforce copy-on-write. + ensureCapacity_unsynchronized(count); + value[index] = ch; + } + + /** + * Append the <code>String</code> value of the argument to this + * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert + * to <code>String</code>. + * + * @param obj the <code>Object</code> to convert and append + * @return this <code>StringBuffer</code> + * @see String#valueOf(Object) + * @see #append(String) + */ + public AbstractStringBuffer append(Object obj) + { + return append(String.valueOf(obj)); + } + + /** + * Append the <code>String</code> to this <code>StringBuffer</code>. If + * str is null, the String "null" is appended. + * + * @param str the <code>String</code> to append + * @return this <code>StringBuffer</code> + */ + public AbstractStringBuffer append(String str) + { + if (str == null) + str = "null"; + int len = str.count; + ensureCapacity_unsynchronized(count + len); + str.getChars(0, len, value, count); + count += len; + return this; + } + + /** + * Append the <code>StringBuilder</code> value of the argument to this + * <code>StringBuilder</code>. This behaves the same as + * <code>append((Object) stringBuffer)</code>, except it is more efficient. + * + * @param stringBuffer the <code>StringBuilder</code> to convert and append + * @return this <code>StringBuilder</code> + * @see #append(Object) + */ + public AbstractStringBuffer append(StringBuffer stringBuffer) + { + if (stringBuffer == null) + return append("null"); + synchronized (stringBuffer) + { + int len = stringBuffer.count; + ensureCapacity(count + len); + VMSystem.arraycopy(stringBuffer.value, 0, value, count, len); + count += len; + } + return this; + } + + /** + * Append the <code>char</code> array to this <code>StringBuffer</code>. + * This is similar (but more efficient) than + * <code>append(new String(data))</code>, except in the case of null. + * + * @param data the <code>char[]</code> to append + * @return this <code>StringBuffer</code> + * @throws NullPointerException if <code>str</code> is <code>null</code> + * @see #append(char[], int, int) + */ + public AbstractStringBuffer append(char[] data) + { + return append(data, 0, data.length); + } + + /** + * Append part of the <code>char</code> array to this + * <code>StringBuffer</code>. This is similar (but more efficient) than + * <code>append(new String(data, offset, count))</code>, except in the case + * of null. + * + * @param data the <code>char[]</code> to append + * @param offset the start location in <code>str</code> + * @param count the number of characters to get from <code>str</code> + * @return this <code>StringBuffer</code> + * @throws NullPointerException if <code>str</code> is <code>null</code> + * @throws IndexOutOfBoundsException if offset or count is out of range + * (while unspecified, this is a StringIndexOutOfBoundsException) + */ + public AbstractStringBuffer append(char[] data, int offset, int count) + { + if (offset < 0 || count < 0 || offset > data.length - count) + throw new StringIndexOutOfBoundsException(); + ensureCapacity_unsynchronized(this.count + count); + VMSystem.arraycopy(data, offset, value, this.count, count); + this.count += count; + return this; + } + + /** + * Append the <code>String</code> value of the argument to this + * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert + * to <code>String</code>. + * + * @param bool the <code>boolean</code> to convert and append + * @return this <code>StringBuffer</code> + * @see String#valueOf(boolean) + */ + public AbstractStringBuffer append(boolean bool) + { + return append(bool ? "true" : "false"); + } + + /** + * Append the <code>char</code> to this <code>StringBuffer</code>. + * + * @param ch the <code>char</code> to append + * @return this <code>StringBuffer</code> + */ + public AbstractStringBuffer append(char ch) + { + ensureCapacity_unsynchronized(count + 1); + value[count++] = ch; + return this; + } + + /** + * Append the characters in the <code>CharSequence</code> to this + * buffer. + * + * @param seq the <code>CharSequence</code> providing the characters + * @return this <code>StringBuffer</code> + * @since 1.5 + */ + public AbstractStringBuffer append(CharSequence seq) + { + return append(seq, 0, seq.length()); + } + + /** + * Append some characters from the <code>CharSequence</code> to this + * buffer. If the argument is null, the <code>seq</code> is assumed + * to be equal to the string <code>"null"</code>. + * + * @param seq the <code>CharSequence</code> providing the characters + * @param start the starting index + * @param end one past the final index + * @return this <code>StringBuffer</code> + * @since 1.5 + */ + public AbstractStringBuffer append(CharSequence seq, int start, int end) + { + if (seq == null) + seq = "null"; + if (end - start > 0) + { + ensureCapacity_unsynchronized(count + end - start); + for (; start < end; ++start) + value[count++] = seq.charAt(start); + } + return this; + } + + /** + * Append the <code>String</code> value of the argument to this + * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert + * to <code>String</code>. + * + * @param inum the <code>int</code> to convert and append + * @return this <code>StringBuffer</code> + * @see String#valueOf(int) + */ + // This is native in libgcj, for efficiency. + public AbstractStringBuffer append(int inum) + { + return append(String.valueOf(inum)); + } + + /** + * Append the <code>String</code> value of the argument to this + * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert + * to <code>String</code>. + * + * @param lnum the <code>long</code> to convert and append + * @return this <code>StringBuffer</code> + * @see String#valueOf(long) + */ + public AbstractStringBuffer append(long lnum) + { + return append(Long.toString(lnum, 10)); + } + + /** + * Append the <code>String</code> value of the argument to this + * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert + * to <code>String</code>. + * + * @param fnum the <code>float</code> to convert and append + * @return this <code>StringBuffer</code> + * @see String#valueOf(float) + */ + public AbstractStringBuffer append(float fnum) + { + return append(Float.toString(fnum)); + } + + /** + * Append the <code>String</code> value of the argument to this + * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert + * to <code>String</code>. + * + * @param dnum the <code>double</code> to convert and append + * @return this <code>StringBuffer</code> + * @see String#valueOf(double) + */ + public AbstractStringBuffer append(double dnum) + { + return append(Double.toString(dnum)); + } + + /** + * Append the code point to this <code>StringBuffer</code>. + * This is like #append(char), but will append two characters + * if a supplementary code point is given. + * + * @param code the code point to append + * @return this <code>StringBuffer</code> + * @see Character#toChars(int, char[], int) + * @since 1.5 + */ + public AbstractStringBuffer appendCodePoint(int code) + { + int len = Character.charCount(code); + ensureCapacity_unsynchronized(count + len); + Character.toChars(code, value, count); + count += len; + return this; + } + + /** + * Delete characters from this <code>StringBuffer</code>. + * <code>delete(10, 12)</code> will delete 10 and 11, but not 12. It is + * harmless for end to be larger than length(). + * + * @param start the first character to delete + * @param end the index after the last character to delete + * @return this <code>StringBuffer</code> + * @throws StringIndexOutOfBoundsException if start or end are out of bounds + * @since 1.2 + */ + public AbstractStringBuffer delete(int start, int end) + { + if (start < 0 || start > count || start > end) + throw new StringIndexOutOfBoundsException(start); + if (end > count) + end = count; + ensureCapacity_unsynchronized(count); + if (count - end != 0) + VMSystem.arraycopy(value, end, value, start, count - end); + count -= end - start; + return this; + } + + /** + * Delete a character from this <code>StringBuffer</code>. + * + * @param index the index of the character to delete + * @return this <code>StringBuffer</code> + * @throws StringIndexOutOfBoundsException if index is out of bounds + * @since 1.2 + */ + public AbstractStringBuffer deleteCharAt(int index) + { + return delete(index, index + 1); + } + + /** + * Replace characters between index <code>start</code> (inclusive) and + * <code>end</code> (exclusive) with <code>str</code>. If <code>end</code> + * is larger than the size of this StringBuffer, all characters after + * <code>start</code> are replaced. + * + * @param start the beginning index of characters to delete (inclusive) + * @param end the ending index of characters to delete (exclusive) + * @param str the new <code>String</code> to insert + * @return this <code>StringBuffer</code> + * @throws StringIndexOutOfBoundsException if start or end are out of bounds + * @throws NullPointerException if str is null + * @since 1.2 + */ + public AbstractStringBuffer replace(int start, int end, String str) + { + if (start < 0 || start > count || start > end) + throw new StringIndexOutOfBoundsException(start); + + int len = str.count; + // Calculate the difference in 'count' after the replace. + int delta = len - (end > count ? count : end) + start; + ensureCapacity_unsynchronized(count + delta); + + if (delta != 0 && end < count) + VMSystem.arraycopy(value, end, value, end + delta, count - end); + + str.getChars(0, len, value, start); + count += delta; + return this; + } + + /** + * Insert a subarray of the <code>char[]</code> argument into this + * <code>StringBuffer</code>. + * + * @param offset the place to insert in this buffer + * @param str the <code>char[]</code> to insert + * @param str_offset the index in <code>str</code> to start inserting from + * @param len the number of characters to insert + * @return this <code>StringBuffer</code> + * @throws NullPointerException if <code>str</code> is <code>null</code> + * @throws StringIndexOutOfBoundsException if any index is out of bounds + * @since 1.2 + */ + public AbstractStringBuffer insert(int offset, char[] str, int str_offset, int len) + { + if (offset < 0 || offset > count || len < 0 + || str_offset < 0 || str_offset > str.length - len) + throw new StringIndexOutOfBoundsException(); + ensureCapacity_unsynchronized(count + len); + VMSystem.arraycopy(value, offset, value, offset + len, count - offset); + VMSystem.arraycopy(str, str_offset, value, offset, len); + count += len; + return this; + } + + /** + * Insert the <code>String</code> value of the argument into this + * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert + * to <code>String</code>. + * + * @param offset the place to insert in this buffer + * @param obj the <code>Object</code> to convert and insert + * @return this <code>StringBuffer</code> + * @exception StringIndexOutOfBoundsException if offset is out of bounds + * @see String#valueOf(Object) + */ + public AbstractStringBuffer insert(int offset, Object obj) + { + return insert(offset, obj == null ? "null" : obj.toString()); + } + + /** + * Insert the <code>String</code> argument into this + * <code>StringBuffer</code>. If str is null, the String "null" is used + * instead. + * + * @param offset the place to insert in this buffer + * @param str the <code>String</code> to insert + * @return this <code>StringBuffer</code> + * @throws StringIndexOutOfBoundsException if offset is out of bounds + */ + public AbstractStringBuffer insert(int offset, String str) + { + if (offset < 0 || offset > count) + throw new StringIndexOutOfBoundsException(offset); + if (str == null) + str = "null"; + int len = str.count; + ensureCapacity_unsynchronized(count + len); + VMSystem.arraycopy(value, offset, value, offset + len, count - offset); + str.getChars(0, len, value, offset); + count += len; + return this; + } + + /** + * Insert the <code>CharSequence</code> argument into this + * <code>StringBuffer</code>. If the sequence is null, the String + * "null" is used instead. + * + * @param offset the place to insert in this buffer + * @param sequence the <code>CharSequence</code> to insert + * @return this <code>StringBuffer</code> + * @throws IndexOutOfBoundsException if offset is out of bounds + * @since 1.5 + */ + public AbstractStringBuffer insert(int offset, CharSequence sequence) + { + if (sequence == null) + sequence = "null"; + return insert(offset, sequence, 0, sequence.length()); + } + + /** + * Insert a subsequence of the <code>CharSequence</code> argument into this + * <code>StringBuffer</code>. If the sequence is null, the String + * "null" is used instead. + * + * @param offset the place to insert in this buffer + * @param sequence the <code>CharSequence</code> to insert + * @param start the starting index of the subsequence + * @param end one past the ending index of the subsequence + * @return this <code>StringBuffer</code> + * @throws IndexOutOfBoundsException if offset, start, + * or end are out of bounds + * @since 1.5 + */ + public AbstractStringBuffer insert(int offset, CharSequence sequence, int start, int end) + { + if (sequence == null) + sequence = "null"; + if (start < 0 || end < 0 || start > end || end > sequence.length()) + throw new IndexOutOfBoundsException(); + int len = end - start; + ensureCapacity_unsynchronized(count + len); + VMSystem.arraycopy(value, offset, value, offset + len, count - offset); + for (int i = start; i < end; ++i) + value[offset++] = sequence.charAt(i); + count += len; + return this; + } + + /** + * Insert the <code>char[]</code> argument into this + * <code>StringBuffer</code>. + * + * @param offset the place to insert in this buffer + * @param data the <code>char[]</code> to insert + * @return this <code>StringBuffer</code> + * @throws NullPointerException if <code>data</code> is <code>null</code> + * @throws StringIndexOutOfBoundsException if offset is out of bounds + * @see #insert(int, char[], int, int) + */ + public AbstractStringBuffer insert(int offset, char[] data) + { + return insert(offset, data, 0, data.length); + } + + /** + * Insert the <code>String</code> value of the argument into this + * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert + * to <code>String</code>. + * + * @param offset the place to insert in this buffer + * @param bool the <code>boolean</code> to convert and insert + * @return this <code>StringBuffer</code> + * @throws StringIndexOutOfBoundsException if offset is out of bounds + * @see String#valueOf(boolean) + */ + public AbstractStringBuffer insert(int offset, boolean bool) + { + return insert(offset, bool ? "true" : "false"); + } + + /** + * Insert the <code>char</code> argument into this <code>StringBuffer</code>. + * + * @param offset the place to insert in this buffer + * @param ch the <code>char</code> to insert + * @return this <code>StringBuffer</code> + * @throws StringIndexOutOfBoundsException if offset is out of bounds + */ + public AbstractStringBuffer insert(int offset, char ch) + { + if (offset < 0 || offset > count) + throw new StringIndexOutOfBoundsException(offset); + ensureCapacity_unsynchronized(count + 1); + VMSystem.arraycopy(value, offset, value, offset + 1, count - offset); + value[offset] = ch; + count++; + return this; + } + + /** + * Insert the <code>String</code> value of the argument into this + * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert + * to <code>String</code>. + * + * @param offset the place to insert in this buffer + * @param inum the <code>int</code> to convert and insert + * @return this <code>StringBuffer</code> + * @throws StringIndexOutOfBoundsException if offset is out of bounds + * @see String#valueOf(int) + */ + public AbstractStringBuffer insert(int offset, int inum) + { + return insert(offset, String.valueOf(inum)); + } + + /** + * Insert the <code>String</code> value of the argument into this + * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert + * to <code>String</code>. + * + * @param offset the place to insert in this buffer + * @param lnum the <code>long</code> to convert and insert + * @return this <code>StringBuffer</code> + * @throws StringIndexOutOfBoundsException if offset is out of bounds + * @see String#valueOf(long) + */ + public AbstractStringBuffer insert(int offset, long lnum) + { + return insert(offset, Long.toString(lnum, 10)); + } + + /** + * Insert the <code>String</code> value of the argument into this + * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert + * to <code>String</code>. + * + * @param offset the place to insert in this buffer + * @param fnum the <code>float</code> to convert and insert + * @return this <code>StringBuffer</code> + * @throws StringIndexOutOfBoundsException if offset is out of bounds + * @see String#valueOf(float) + */ + public AbstractStringBuffer insert(int offset, float fnum) + { + return insert(offset, Float.toString(fnum)); + } + + /** + * Insert the <code>String</code> value of the argument into this + * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert + * to <code>String</code>. + * + * @param offset the place to insert in this buffer + * @param dnum the <code>double</code> to convert and insert + * @return this <code>StringBuffer</code> + * @throws StringIndexOutOfBoundsException if offset is out of bounds + * @see String#valueOf(double) + */ + public AbstractStringBuffer insert(int offset, double dnum) + { + return insert(offset, Double.toString(dnum)); + } + + /** + * Finds the first instance of a substring in this StringBuilder. + * + * @param str String to find + * @return location (base 0) of the String, or -1 if not found + * @throws NullPointerException if str is null + * @see #indexOf(String, int) + */ + public int indexOf(String str) + { + return indexOf(str, 0); + } + + /** + * Finds the first instance of a String in this StringBuffer, starting at + * a given index. If starting index is less than 0, the search starts at + * the beginning of this String. If the starting index is greater than the + * length of this String, or the substring is not found, -1 is returned. + * + * @param str String to find + * @param fromIndex index to start the search + * @return location (base 0) of the String, or -1 if not found + * @throws NullPointerException if str is null + * @since 1.4 + */ + public int indexOf(String str, int fromIndex) + { + if (fromIndex < 0) + fromIndex = 0; + int limit = count - str.count; + for ( ; fromIndex <= limit; fromIndex++) + if (regionMatches(fromIndex, str)) + return fromIndex; + return -1; + } + + /** + * Finds the last instance of a substring in this StringBuffer. + * + * @param str String to find + * @return location (base 0) of the String, or -1 if not found + * @throws NullPointerException if str is null + * @see #lastIndexOf(String, int) + * @since 1.4 + */ + public int lastIndexOf(String str) + { + return lastIndexOf(str, count - str.count); + } + + /** + * Finds the last instance of a String in this StringBuffer, starting at a + * given index. If starting index is greater than the maximum valid index, + * then the search begins at the end of this String. If the starting index + * is less than zero, or the substring is not found, -1 is returned. + * + * @param str String to find + * @param fromIndex index to start the search + * @return location (base 0) of the String, or -1 if not found + * @throws NullPointerException if str is null + * @since 1.4 + */ + public int lastIndexOf(String str, int fromIndex) + { + fromIndex = Math.min(fromIndex, count - str.count); + for ( ; fromIndex >= 0; fromIndex--) + if (regionMatches(fromIndex, str)) + return fromIndex; + return -1; + } + + /** + * Reverse the characters in this StringBuffer. The same sequence of + * characters exists, but in the reverse index ordering. + * + * @return this <code>StringBuffer</code> + */ + public AbstractStringBuffer reverse() + { + // Call ensureCapacity to enforce copy-on-write. + ensureCapacity_unsynchronized(count); + for (int i = count >> 1, j = count - i; --i >= 0; ++j) + { + char c = value[i]; + value[i] = value[j]; + value[j] = c; + } + return this; + } + + /** + * This may reduce the amount of memory used by the StringBuffer, + * by resizing the internal array to remove unused space. However, + * this method is not required to resize, so this behavior cannot + * be relied upon. + * @since 1.5 + */ + public void trimToSize() + { + int wouldSave = value.length - count; + // Some random heuristics: if we save less than 20 characters, who + // cares. + if (wouldSave < 20) + return; + // If we save more than 200 characters, shrink. + // If we save more than 1/4 of the buffer, shrink. + if (wouldSave > 200 || wouldSave * 4 > value.length) + { + char[] newValue = new char[count]; + VMSystem.arraycopy(value, 0, newValue, 0, count); + value = newValue; + } + } + + /** + * Return the number of code points between two indices in the + * <code>StringBuffer</code>. An unpaired surrogate counts as a + * code point for this purpose. Characters outside the indicated + * range are not examined, even if the range ends in the middle of a + * surrogate pair. + * + * @param start the starting index + * @param end one past the ending index + * @return the number of code points + * @since 1.5 + */ + public int codePointCount(int start, int end) + { + if (start < 0 || end >= count || start > end) + throw new StringIndexOutOfBoundsException(); + + int count = 0; + while (start < end) + { + char base = value[start]; + if (base < Character.MIN_HIGH_SURROGATE + || base > Character.MAX_HIGH_SURROGATE + || start == end + || start == count + || value[start + 1] < Character.MIN_LOW_SURROGATE + || value[start + 1] > Character.MAX_LOW_SURROGATE) + { + // Nothing. + } + else + { + // Surrogate pair. + ++start; + } + ++start; + ++count; + } + return count; + } + + /** + * Starting at the given index, this counts forward by the indicated + * number of code points, and then returns the resulting index. An + * unpaired surrogate counts as a single code point for this + * purpose. + * + * @param start the starting index + * @param codePoints the number of code points + * @return the resulting index + * @since 1.5 + */ + public int offsetByCodePoints(int start, int codePoints) + { + while (codePoints > 0) + { + char base = value[start]; + if (base < Character.MIN_HIGH_SURROGATE + || base > Character.MAX_HIGH_SURROGATE + || start == count + || value[start + 1] < Character.MIN_LOW_SURROGATE + || value[start + 1] > Character.MAX_LOW_SURROGATE) + { + // Nothing. + } + else + { + // Surrogate pair. + ++start; + } + ++start; + --codePoints; + } + return start; + } + + /** + * Increase the capacity of this <code>StringBuilder</code>. This will + * ensure that an expensive growing operation will not occur until + * <code>minimumCapacity</code> is reached. The buffer is grown to the + * larger of <code>minimumCapacity</code> and + * <code>capacity() * 2 + 2</code>, if it is not already large enough. + * + * @param minimumCapacity the new capacity + * @see #capacity() + */ + void ensureCapacity_unsynchronized(int minimumCapacity) + { + if (minimumCapacity > value.length) + { + int max = value.length * 2 + 2; + minimumCapacity = (minimumCapacity < max ? max : minimumCapacity); + char[] nb = new char[minimumCapacity]; + VMSystem.arraycopy(value, 0, nb, 0, count); + value = nb; + } + } + + /** + * Predicate which determines if a substring of this matches another String + * starting at a specified offset for each String and continuing for a + * specified length. This is more efficient than creating a String to call + * indexOf on. + * + * @param toffset index to start comparison at for this String + * @param other non-null String to compare to region of this + * @return true if regions match, false otherwise + * @see #indexOf(String, int) + * @see #lastIndexOf(String, int) + * @see String#regionMatches(boolean, int, String, int, int) + */ + private boolean regionMatches(int toffset, String other) + { + int len = other.count; + int index = other.offset; + while (--len >= 0) + if (value[toffset++] != other.value[index++]) + return false; + return true; + } + +} diff --git a/libjava/classpath/java/lang/Byte.java b/libjava/classpath/java/lang/Byte.java index 7f53a494b95..a1536e1be1b 100644 --- a/libjava/classpath/java/lang/Byte.java +++ b/libjava/classpath/java/lang/Byte.java @@ -88,6 +88,11 @@ public final class Byte extends Number implements Comparable<Byte> // This caches Byte values, and is used by boxing conversions via // valueOf(). We're required to cache all possible values here. private static Byte[] byteCache = new Byte[MAX_VALUE - MIN_VALUE + 1]; + static + { + for (int i=MIN_VALUE; i <= MAX_VALUE; i++) + byteCache[i - MIN_VALUE] = new Byte((byte) i); + } /** @@ -185,7 +190,7 @@ public final class Byte extends Number implements Comparable<Byte> */ public static Byte valueOf(String s, int radix) { - return new Byte(parseByte(s, radix)); + return valueOf(parseByte(s, radix)); } /** @@ -201,7 +206,7 @@ public final class Byte extends Number implements Comparable<Byte> */ public static Byte valueOf(String s) { - return new Byte(parseByte(s, 10)); + return valueOf(parseByte(s, 10)); } /** @@ -214,12 +219,7 @@ public final class Byte extends Number implements Comparable<Byte> */ public static Byte valueOf(byte val) { - synchronized (byteCache) - { - if (byteCache[val - MIN_VALUE] == null) - byteCache[val - MIN_VALUE] = new Byte(val); - return byteCache[val - MIN_VALUE]; - } + return byteCache[val - MIN_VALUE]; } /** @@ -258,7 +258,7 @@ public final class Byte extends Number implements Comparable<Byte> int i = Integer.parseInt(s, 10, true); if ((byte) i != i) throw new NumberFormatException(); - return new Byte((byte) i); + return valueOf((byte) i); } /** diff --git a/libjava/classpath/java/lang/Character.java b/libjava/classpath/java/lang/Character.java index 506033f31bc..eaa9557f651 100644 --- a/libjava/classpath/java/lang/Character.java +++ b/libjava/classpath/java/lang/Character.java @@ -2055,6 +2055,11 @@ public final class Character implements Serializable, Comparable<Character> // this constant controls how much we actually cache. private static final int MAX_CACHE = 127; private static Character[] charCache = new Character[MAX_CACHE + 1]; + static + { + for (char i=0; i <= MAX_CACHE; i++) + charCache[i] = new Character(i); + } /** * Lu = Letter, Uppercase (Informative). @@ -4208,12 +4213,8 @@ public final class Character implements Serializable, Comparable<Character> { if (val > MAX_CACHE) return new Character(val); - synchronized (charCache) - { - if (charCache[val - MIN_VALUE] == null) - charCache[val - MIN_VALUE] = new Character(val); - return charCache[val - MIN_VALUE]; - } + else + return charCache[val - MIN_VALUE]; } /** diff --git a/libjava/classpath/java/lang/ClassLoader.java b/libjava/classpath/java/lang/ClassLoader.java index 3d7c32cc935..591406ac4dc 100644 --- a/libjava/classpath/java/lang/ClassLoader.java +++ b/libjava/classpath/java/lang/ClassLoader.java @@ -659,7 +659,7 @@ public abstract class ClassLoader */ protected Enumeration<URL> findResources(String name) throws IOException { - return (Enumeration<URL>) EmptyEnumeration.getInstance(); + return new EmptyEnumeration<URL>(); } /** diff --git a/libjava/classpath/java/lang/Double.java b/libjava/classpath/java/lang/Double.java index 466d48205ea..f3f7cb1e0ec 100644 --- a/libjava/classpath/java/lang/Double.java +++ b/libjava/classpath/java/lang/Double.java @@ -38,6 +38,7 @@ exception statement from your version. */ package java.lang; +import gnu.java.lang.CPStringBuilder; /** * Instances of class <code>Double</code> represent primitive @@ -103,6 +104,16 @@ public final class Double extends Number implements Comparable<Double> public static final Class<Double> TYPE = (Class<Double>) VMClassLoader.getPrimitiveClass('D'); /** + * Cache representation of 0 + */ + private static final Double ZERO = new Double(0.0d); + + /** + * Cache representation of 1 + */ + private static final Double ONE = new Double(1.0d); + + /** * The immutable value of this Double. * * @serial the wrapped double @@ -201,7 +212,7 @@ public final class Double extends Number implements Comparable<Double> return d < 0 ? "-Infinity" : "Infinity"; long bits = doubleToLongBits(d); - StringBuilder result = new StringBuilder(); + CPStringBuilder result = new CPStringBuilder(); if (bits < 0) result.append('-'); @@ -260,8 +271,12 @@ public final class Double extends Number implements Comparable<Double> */ public static Double valueOf(double val) { - // We don't actually cache, but we could. - return new Double(val); + if ((val == 0.0) && (doubleToRawLongBits(val) == 0L)) + return ZERO; + else if (val == 1.0) + return ONE; + else + return new Double(val); } /** @@ -276,7 +291,7 @@ public final class Double extends Number implements Comparable<Double> */ public static Double valueOf(String s) { - return new Double(parseDouble(s)); + return valueOf(parseDouble(s)); } /** @@ -489,17 +504,13 @@ public final class Double extends Number implements Comparable<Double> */ public boolean equals(Object obj) { - if (! (obj instanceof Double)) - return false; - - double d = ((Double) obj).value; - - // Avoid call to native method. However, some implementations, like gcj, - // are better off using floatToIntBits(value) == floatToIntBits(f). - // Check common case first, then check NaN and 0. - if (value == d) - return (value != 0) || (1 / value == 1 / d); - return isNaN(value) && isNaN(d); + if (obj instanceof Double) + { + double d = ((Double) obj).value; + return (doubleToRawLongBits(value) == doubleToRawLongBits(d)) || + (isNaN(value) && isNaN(d)); + } + return false; } /** diff --git a/libjava/classpath/java/lang/Enum.java b/libjava/classpath/java/lang/Enum.java index fa217bb67a6..da2e40b8e05 100644 --- a/libjava/classpath/java/lang/Enum.java +++ b/libjava/classpath/java/lang/Enum.java @@ -89,7 +89,6 @@ public abstract class Enum<T extends Enum<T>> * @exception IllegalArgumentException when there is no value s in * the enum etype. */ - @SuppressWarnings("unchecked") public static <S extends Enum<S>> S valueOf(Class<S> etype, String s) { if (etype == null || s == null) @@ -103,7 +102,9 @@ public abstract class Enum<T extends Enum<T>> if (! f.isEnumConstant()) throw new IllegalArgumentException(s); Class.setAccessible(f); - return (S) f.get(null); + @SuppressWarnings("unchecked") + S val = (S) f.get(null); + return val; } catch (NoSuchFieldException exception) { diff --git a/libjava/classpath/java/lang/Float.java b/libjava/classpath/java/lang/Float.java index 72f31b57eb4..63e43c257ea 100644 --- a/libjava/classpath/java/lang/Float.java +++ b/libjava/classpath/java/lang/Float.java @@ -39,6 +39,8 @@ exception statement from your version. */ package java.lang; +import gnu.java.lang.CPStringBuilder; + /** * Instances of class <code>Float</code> represent primitive * <code>float</code> values. @@ -102,6 +104,16 @@ public final class Float extends Number implements Comparable<Float> public static final int SIZE = 32; /** + * Cache representation of 0 + */ + private static final Float ZERO = new Float(0.0f); + + /** + * Cache representation of 1 + */ + private static final Float ONE = new Float(1.0f); + + /** * The immutable value of this Float. * * @serial the wrapped float @@ -211,7 +223,7 @@ public final class Float extends Number implements Comparable<Float> return f < 0 ? "-Infinity" : "Infinity"; int bits = floatToIntBits(f); - StringBuilder result = new StringBuilder(); + CPStringBuilder result = new CPStringBuilder(); if (bits < 0) result.append('-'); @@ -273,7 +285,7 @@ public final class Float extends Number implements Comparable<Float> */ public static Float valueOf(String s) { - return new Float(parseFloat(s)); + return valueOf(parseFloat(s)); } /** @@ -287,8 +299,12 @@ public final class Float extends Number implements Comparable<Float> */ public static Float valueOf(float val) { - // We don't actually cache, but we could. - return new Float(val); + if ((val == 0.0) && (floatToRawIntBits(val) == 0)) + return ZERO; + else if (val == 1.0) + return ONE; + else + return new Float(val); } /** @@ -498,17 +514,13 @@ public final class Float extends Number implements Comparable<Float> */ public boolean equals(Object obj) { - if (! (obj instanceof Float)) - return false; - - float f = ((Float) obj).value; - - // Avoid call to native method. However, some implementations, like gcj, - // are better off using floatToIntBits(value) == floatToIntBits(f). - // Check common case first, then check NaN and 0. - if (value == f) - return (value != 0) || (1 / value == 1 / f); - return isNaN(value) && isNaN(f); + if (obj instanceof Float) + { + float f = ((Float) obj).value; + return (floatToRawIntBits(value) == floatToRawIntBits(f)) || + (isNaN(value) && isNaN(f)); + } + return false; } /** diff --git a/libjava/classpath/java/lang/InheritableThreadLocal.java b/libjava/classpath/java/lang/InheritableThreadLocal.java index 2079a4c20ff..07d52b5d08c 100644 --- a/libjava/classpath/java/lang/InheritableThreadLocal.java +++ b/libjava/classpath/java/lang/InheritableThreadLocal.java @@ -37,10 +37,6 @@ exception statement from your version. */ package java.lang; -import gnu.java.util.WeakIdentityHashMap; - -import java.util.Iterator; - /** * A ThreadLocal whose value is inherited by child Threads. The value of the * InheritableThreadLocal associated with the (parent) Thread is copied to @@ -97,24 +93,6 @@ public class InheritableThreadLocal<T> extends ThreadLocal<T> { // The currentThread is the parent of the new thread. Thread parentThread = Thread.currentThread(); - if (parentThread.locals != null) - { - Iterator keys = parentThread.locals.keySet().iterator(); - while (keys.hasNext()) - { - Object key = keys.next(); - if (key instanceof InheritableThreadLocal) - { - InheritableThreadLocal local = (InheritableThreadLocal)key; - Object parentValue = parentThread.locals.get(key); - Object childValue = local.childValue(parentValue == sentinel - ? null : parentValue); - if (childThread.locals == null) - childThread.locals = new WeakIdentityHashMap(); - childThread.locals.put(key, (childValue == null - ? sentinel : childValue)); - } - } - } + childThread.locals.inherit(parentThread.locals); } } diff --git a/libjava/classpath/java/lang/Integer.java b/libjava/classpath/java/lang/Integer.java index cbf5274f0fc..e5ca4b3428e 100644 --- a/libjava/classpath/java/lang/Integer.java +++ b/libjava/classpath/java/lang/Integer.java @@ -52,6 +52,7 @@ package java.lang; * @author Eric Blake (ebb9@email.byu.edu) * @author Tom Tromey (tromey@redhat.com) * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @author Ian Rogers * @since 1.0 * @status updated to 1.5 */ @@ -92,7 +93,12 @@ public final class Integer extends Number implements Comparable<Integer> // these constants control how much we actually cache. private static final int MIN_CACHE = -128; private static final int MAX_CACHE = 127; - private static Integer[] intCache = new Integer[MAX_CACHE - MIN_CACHE + 1]; + private static final Integer[] intCache = new Integer[MAX_CACHE - MIN_CACHE + 1]; + static + { + for (int i=MIN_CACHE; i <= MAX_CACHE; i++) + intCache[i - MIN_CACHE] = new Integer(i); + } /** * The immutable value of this Integer. @@ -126,6 +132,45 @@ public final class Integer extends Number implements Comparable<Integer> } /** + * Return the size of a string large enough to hold the given number + * + * @param num the number we want the string length for (must be positive) + * @param radix the radix (base) that will be used for the string + * @return a size sufficient for a string of num + */ + private static int stringSize(int num, int radix) { + int exp; + if (radix < 4) + { + exp = 1; + } + else if (radix < 8) + { + exp = 2; + } + else if (radix < 16) + { + exp = 3; + } + else if (radix < 32) + { + exp = 4; + } + else + { + exp = 5; + } + int size=0; + do + { + num >>>= exp; + size++; + } + while(num != 0); + return size; + } + + /** * Converts the <code>int</code> to a <code>String</code> using * the specified radix (base). If the radix exceeds * <code>Character.MIN_RADIX</code> or <code>Character.MAX_RADIX</code>, 10 @@ -142,22 +187,40 @@ public final class Integer extends Number implements Comparable<Integer> if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) radix = 10; - // For negative numbers, print out the absolute value w/ a leading '-'. - // Use an array large enough for a binary number. - char[] buffer = new char[33]; - int i = 33; - boolean isNeg = false; - if (num < 0) + // Is the value negative? + boolean isNeg = num < 0; + + // Is the string a single character? + if (!isNeg && num < radix) + return new String(digits, num, 1, true); + + // Compute string size and allocate buffer + // account for a leading '-' if the value is negative + int size; + int i; + char[] buffer; + if (isNeg) { - isNeg = true; num = -num; // When the value is MIN_VALUE, it overflows when made positive if (num < 0) { + i = size = stringSize(MAX_VALUE, radix) + 2; + buffer = new char[size]; buffer[--i] = digits[(int) (-(num + radix) % radix)]; num = -(num / radix); } + else + { + i = size = stringSize(num, radix) + 1; + buffer = new char[size]; + } + } + else + { + i = size = stringSize(num, radix); + buffer = new char[size]; } do @@ -171,7 +234,7 @@ public final class Integer extends Number implements Comparable<Integer> buffer[--i] = '-'; // Package constructor avoids an array copy. - return new String(buffer, i, 33 - i, true); + return new String(buffer, i, size - i, true); } /** @@ -275,7 +338,7 @@ public final class Integer extends Number implements Comparable<Integer> */ public static Integer valueOf(String s, int radix) { - return new Integer(parseInt(s, radix, false)); + return valueOf(parseInt(s, radix, false)); } /** @@ -291,7 +354,7 @@ public final class Integer extends Number implements Comparable<Integer> */ public static Integer valueOf(String s) { - return new Integer(parseInt(s, 10, false)); + return valueOf(parseInt(s, 10, false)); } /** @@ -306,12 +369,8 @@ public final class Integer extends Number implements Comparable<Integer> { if (val < MIN_CACHE || val > MAX_CACHE) return new Integer(val); - synchronized (intCache) - { - if (intCache[val - MIN_CACHE] == null) - intCache[val - MIN_CACHE] = new Integer(val); - return intCache[val - MIN_CACHE]; - } + else + return intCache[val - MIN_CACHE]; } /** @@ -440,7 +499,7 @@ public final class Integer extends Number implements Comparable<Integer> public static Integer getInteger(String nm, int val) { Integer result = getInteger(nm, null); - return result == null ? new Integer(val) : result; + return result == null ? valueOf(val) : result; } /** @@ -506,7 +565,7 @@ public final class Integer extends Number implements Comparable<Integer> */ public static Integer decode(String str) { - return new Integer(parseInt(str, 10, true)); + return valueOf(parseInt(str, 10, true)); } /** @@ -628,7 +687,14 @@ public final class Integer extends Number implements Comparable<Integer> */ public static int signum(int x) { - return x < 0 ? -1 : (x > 0 ? 1 : 0); + return (x >> 31) | (-x >>> 31); + + // The LHS propagates the sign bit through every bit in the word; + // if X < 0, every bit is set to 1, else 0. if X > 0, the RHS + // negates x and shifts the resulting 1 in the sign bit to the + // LSB, leaving every other bit 0. + + // Hacker's Delight, Section 2-7 } /** @@ -666,10 +732,22 @@ public final class Integer extends Number implements Comparable<Integer> // Package visible for use by Long. static String toUnsignedString(int num, int exp) { - // Use an array large enough for a binary number. + // Compute string length + int size = 1; + int copy = num >>> exp; + while (copy != 0) + { + size++; + copy >>>= exp; + } + // Quick path for single character strings + if (size == 1) + return new String(digits, num, 1, true); + + // Encode into buffer int mask = (1 << exp) - 1; - char[] buffer = new char[32]; - int i = 32; + char[] buffer = new char[size]; + int i = size; do { buffer[--i] = digits[num & mask]; @@ -678,7 +756,7 @@ public final class Integer extends Number implements Comparable<Integer> while (num != 0); // Package constructor avoids an array copy. - return new String(buffer, i, 32 - i, true); + return new String(buffer, i, size - i, true); } /** diff --git a/libjava/classpath/java/lang/Long.java b/libjava/classpath/java/lang/Long.java index 08ac3976ca7..a5ee6c707ad 100644 --- a/libjava/classpath/java/lang/Long.java +++ b/libjava/classpath/java/lang/Long.java @@ -51,6 +51,7 @@ package java.lang; * @author Eric Blake (ebb9@email.byu.edu) * @author Tom Tromey (tromey@redhat.com) * @author Andrew John Hughes (gnu_andrew@member.fsf.org) + * @author Ian Rogers * @since 1.0 * @status updated to 1.5 */ @@ -86,6 +87,18 @@ public final class Long extends Number implements Comparable<Long> */ public static final int SIZE = 64; + // This caches some Long values, and is used by boxing + // conversions via valueOf(). We cache at least -128..127; + // these constants control how much we actually cache. + private static final int MIN_CACHE = -128; + private static final int MAX_CACHE = 127; + private static final Long[] longCache = new Long[MAX_CACHE - MIN_CACHE + 1]; + static + { + for (int i=MIN_CACHE; i <= MAX_CACHE; i++) + longCache[i - MIN_CACHE] = new Long(i); + } + /** * The immutable value of this Long. * @@ -118,6 +131,45 @@ public final class Long extends Number implements Comparable<Long> } /** + * Return the size of a string large enough to hold the given number + * + * @param num the number we want the string length for (must be positive) + * @param radix the radix (base) that will be used for the string + * @return a size sufficient for a string of num + */ + private static int stringSize(long num, int radix) { + int exp; + if (radix < 4) + { + exp = 1; + } + else if (radix < 8) + { + exp = 2; + } + else if (radix < 16) + { + exp = 3; + } + else if (radix < 32) + { + exp = 4; + } + else + { + exp = 5; + } + int size=0; + do + { + num >>>= exp; + size++; + } + while(num != 0); + return size; + } + + /** * Converts the <code>long</code> to a <code>String</code> using * the specified radix (base). If the radix exceeds * <code>Character.MIN_RADIX</code> or <code>Character.MAX_RADIX</code>, 10 @@ -131,29 +183,43 @@ public final class Long extends Number implements Comparable<Long> */ public static String toString(long num, int radix) { - // Use the Integer toString for efficiency if possible. - if ((int) num == num) - return Integer.toString((int) num, radix); - if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) radix = 10; - // For negative numbers, print out the absolute value w/ a leading '-'. - // Use an array large enough for a binary number. - char[] buffer = new char[65]; - int i = 65; - boolean isNeg = false; - if (num < 0) + // Is the value negative? + boolean isNeg = num < 0; + + // Is the string a single character? + if (!isNeg && num < radix) + return new String(digits, (int)num, 1, true); + + // Compute string size and allocate buffer + // account for a leading '-' if the value is negative + int size; + int i; + char[] buffer; + if (isNeg) { - isNeg = true; num = -num; // When the value is MIN_VALUE, it overflows when made positive if (num < 0) - { - buffer[--i] = digits[(int) (-(num + radix) % radix)]; - num = -(num / radix); - } + { + i = size = stringSize(MAX_VALUE, radix) + 2; + buffer = new char[size]; + buffer[--i] = digits[(int) (-(num + radix) % radix)]; + num = -(num / radix); + } + else + { + i = size = stringSize(num, radix) + 1; + buffer = new char[size]; + } + } + else + { + i = size = stringSize(num, radix); + buffer = new char[size]; } do @@ -167,7 +233,7 @@ public final class Long extends Number implements Comparable<Long> buffer[--i] = '-'; // Package constructor avoids an array copy. - return new String(buffer, i, 65 - i, true); + return new String(buffer, i, size - i, true); } /** @@ -270,7 +336,7 @@ public final class Long extends Number implements Comparable<Long> */ public static Long valueOf(String s, int radix) { - return new Long(parseLong(s, radix, false)); + return valueOf(parseLong(s, radix, false)); } /** @@ -286,7 +352,7 @@ public final class Long extends Number implements Comparable<Long> */ public static Long valueOf(String s) { - return new Long(parseLong(s, 10, false)); + return valueOf(parseLong(s, 10, false)); } /** @@ -298,9 +364,10 @@ public final class Long extends Number implements Comparable<Long> */ public static Long valueOf(long val) { - // We aren't required to cache here. We could, though perhaps we - // ought to consider that as an empirical question. - return new Long(val); + if (val < MIN_CACHE || val > MAX_CACHE) + return new Long(val); + else + return longCache[((int)val) - MIN_CACHE]; } /** @@ -337,7 +404,7 @@ public final class Long extends Number implements Comparable<Long> */ public static Long decode(String str) { - return new Long(parseLong(str, 10, true)); + return valueOf(parseLong(str, 10, true)); } /** @@ -467,7 +534,7 @@ public final class Long extends Number implements Comparable<Long> public static Long getLong(String nm, long val) { Long result = getLong(nm, null); - return result == null ? new Long(val) : result; + return result == null ? valueOf(val) : result; } /** @@ -622,7 +689,14 @@ public final class Long extends Number implements Comparable<Long> */ public static int signum(long x) { - return x < 0 ? -1 : (x > 0 ? 1 : 0); + return (int) ((x >> 63) | (-x >>> 63)); + + // The LHS propagates the sign bit through every bit in the word; + // if X < 0, every bit is set to 1, else 0. if X > 0, the RHS + // negates x and shifts the resulting 1 in the sign bit to the + // LSB, leaving every other bit 0. + + // Hacker's Delight, Section 2-7 } /** @@ -655,16 +729,22 @@ public final class Long extends Number implements Comparable<Long> */ private static String toUnsignedString(long num, int exp) { - // Use the Integer toUnsignedString for efficiency if possible. - // If NUM<0 then this particular optimization doesn't work - // properly. - if (num >= 0 && (int) num == num) - return Integer.toUnsignedString((int) num, exp); + // Compute string length + int size = 1; + long copy = num >>> exp; + while (copy != 0) + { + size++; + copy >>>= exp; + } + // Quick path for single character strings + if (size == 1) + return new String(digits, (int)num, 1, true); - // Use an array large enough for a binary number. + // Encode into buffer int mask = (1 << exp) - 1; - char[] buffer = new char[64]; - int i = 64; + char[] buffer = new char[size]; + int i = size; do { buffer[--i] = digits[(int) num & mask]; @@ -673,7 +753,7 @@ public final class Long extends Number implements Comparable<Long> while (num != 0); // Package constructor avoids an array copy. - return new String(buffer, i, 64 - i, true); + return new String(buffer, i, size - i, true); } /** diff --git a/libjava/classpath/java/lang/Short.java b/libjava/classpath/java/lang/Short.java index 41a31e26082..ec87f933e93 100644 --- a/libjava/classpath/java/lang/Short.java +++ b/libjava/classpath/java/lang/Short.java @@ -90,6 +90,11 @@ public final class Short extends Number implements Comparable<Short> private static final int MIN_CACHE = -128; private static final int MAX_CACHE = 127; private static Short[] shortCache = new Short[MAX_CACHE - MIN_CACHE + 1]; + static + { + for (short i=MIN_CACHE; i <= MAX_CACHE; i++) + shortCache[i - MIN_CACHE] = new Short(i); + } /** * The immutable value of this Short. @@ -184,7 +189,7 @@ public final class Short extends Number implements Comparable<Short> */ public static Short valueOf(String s, int radix) { - return new Short(parseShort(s, radix)); + return valueOf(parseShort(s, radix)); } /** @@ -200,7 +205,7 @@ public final class Short extends Number implements Comparable<Short> */ public static Short valueOf(String s) { - return new Short(parseShort(s, 10)); + return valueOf(parseShort(s, 10)); } /** @@ -216,12 +221,8 @@ public final class Short extends Number implements Comparable<Short> { if (val < MIN_CACHE || val > MAX_CACHE) return new Short(val); - synchronized (shortCache) - { - if (shortCache[val - MIN_CACHE] == null) - shortCache[val - MIN_CACHE] = new Short(val); - return shortCache[val - MIN_CACHE]; - } + else + return shortCache[val - MIN_CACHE]; } /** @@ -260,7 +261,7 @@ public final class Short extends Number implements Comparable<Short> int i = Integer.parseInt(s, 10, true); if ((short) i != i) throw new NumberFormatException(); - return new Short((short) i); + return valueOf((short) i); } /** diff --git a/libjava/classpath/java/lang/String.java b/libjava/classpath/java/lang/String.java index 0b56accf708..95c88399d3c 100644 --- a/libjava/classpath/java/lang/String.java +++ b/libjava/classpath/java/lang/String.java @@ -40,6 +40,7 @@ exception statement from your version. */ package java.lang; import gnu.java.lang.CharData; +import gnu.java.lang.CPStringBuilder; import java.io.Serializable; import java.io.UnsupportedEncodingException; @@ -2072,7 +2073,7 @@ public final class String int replaceLength = replacement.length(); int startPos = this.indexOf(targetString); - StringBuilder result = new StringBuilder(this); + CPStringBuilder result = new CPStringBuilder(this); while (startPos != -1) { // Replace the target with the replacement diff --git a/libjava/classpath/java/lang/StringBuffer.java b/libjava/classpath/java/lang/StringBuffer.java index 3aa84a21e12..b105f55da56 100644 --- a/libjava/classpath/java/lang/StringBuffer.java +++ b/libjava/classpath/java/lang/StringBuffer.java @@ -1,5 +1,5 @@ /* StringBuffer.java -- Growable strings - Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 + Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2008 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -73,6 +73,7 @@ import java.io.Serializable; * @status updated to 1.4 */ public final class StringBuffer + extends AbstractStringBuffer implements Serializable, CharSequence, Appendable { // Implementation note: if you change this class, you usually will @@ -84,23 +85,6 @@ public final class StringBuffer private static final long serialVersionUID = 3388685877147921107L; /** - * Index of next available character (and thus the size of the current - * string contents). Note that this has permissions set this way so that - * String can get the value. - * - * @serial the number of characters in the buffer - */ - int count; - - /** - * The buffer. Note that this has permissions set this way so that String - * can get the value. - * - * @serial the buffer - */ - char[] value; - - /** * True if the buffer is shared with another object (StringBuffer or * String); this means the buffer must be copied before writing to it again. * Note that this has permissions set this way so that String can get the @@ -111,16 +95,11 @@ public final class StringBuffer boolean shared; /** - * The default capacity of a buffer. - */ - private static final int DEFAULT_CAPACITY = 16; - - /** * Create a new StringBuffer with default capacity 16. */ public StringBuffer() { - this(DEFAULT_CAPACITY); + super(); } /** @@ -132,7 +111,7 @@ public final class StringBuffer */ public StringBuffer(int capacity) { - value = new char[capacity]; + super(capacity); } /** @@ -146,9 +125,7 @@ public final class StringBuffer public StringBuffer(String str) { // Unfortunately, because the size is 16 larger, we cannot share. - count = str.count; - value = new char[count + DEFAULT_CAPACITY]; - str.getChars(0, count, value, 0); + super(str); } /** @@ -163,11 +140,7 @@ public final class StringBuffer */ public StringBuffer(CharSequence seq) { - int len = seq.length(); - count = len <= 0 ? 0 : len; - value = new char[count + DEFAULT_CAPACITY]; - for (int i = 0; i < len; ++i) - value[i] = seq.charAt(i); + super(seq); } /** @@ -226,29 +199,7 @@ public final class StringBuffer */ public synchronized void setLength(int newLength) { - if (newLength < 0) - throw new StringIndexOutOfBoundsException(newLength); - - int valueLength = value.length; - - /* Always call ensureCapacity_unsynchronized in order to preserve - copy-on-write semantics. */ - ensureCapacity_unsynchronized(newLength); - - if (newLength < valueLength) - { - /* If the StringBuffer's value just grew, then we know that - value is newly allocated and the region between count and - newLength is filled with '\0'. */ - count = newLength; - } - else - { - /* The StringBuffer's value doesn't need to grow. However, - we should clear out any cruft that may exist. */ - while (count < newLength) - value[count++] = '\0'; - } + super.setLength(newLength); } /** @@ -257,12 +208,11 @@ public final class StringBuffer * @param index the index of the character to get, starting at 0 * @return the character at the specified index * @throws IndexOutOfBoundsException if index is negative or >= length() + * (while unspecified, this is a StringIndexOutOfBoundsException) */ public synchronized char charAt(int index) { - if (index < 0 || index >= count) - throw new StringIndexOutOfBoundsException(index); - return value[index]; + return super.charAt(index); } /** @@ -277,7 +227,7 @@ public final class StringBuffer */ public synchronized int codePointAt(int index) { - return Character.codePointAt(value, index, count); + return super.codePointAt(index); } /** @@ -291,11 +241,7 @@ public final class StringBuffer */ public synchronized int codePointBefore(int index) { - // Character.codePointBefore() doesn't perform this check. We - // could use the CharSequence overload, but this is just as easy. - if (index >= count) - throw new IndexOutOfBoundsException(); - return Character.codePointBefore(value, index, 1); + return super.codePointBefore(index); } /** @@ -316,9 +262,7 @@ public final class StringBuffer public synchronized void getChars(int srcOffset, int srcEnd, char[] dst, int dstOffset) { - if (srcOffset < 0 || srcEnd > count || srcEnd < srcOffset) - throw new StringIndexOutOfBoundsException(); - VMSystem.arraycopy(value, srcOffset, dst, dstOffset, srcEnd - srcOffset); + super.getChars(srcOffset, srcEnd, dst, dstOffset); } /** @@ -331,11 +275,7 @@ public final class StringBuffer */ public synchronized void setCharAt(int index, char ch) { - if (index < 0 || index >= count) - throw new StringIndexOutOfBoundsException(index); - // Call ensureCapacity to enforce copy-on-write. - ensureCapacity_unsynchronized(count); - value[index] = ch; + super.setCharAt(index, ch); } /** @@ -348,9 +288,10 @@ public final class StringBuffer * @see String#valueOf(Object) * @see #append(String) */ - public StringBuffer append(Object obj) + public synchronized StringBuffer append(Object obj) { - return append(obj == null ? "null" : obj.toString()); + super.append(obj); + return this; } /** @@ -362,12 +303,7 @@ public final class StringBuffer */ public synchronized StringBuffer append(String str) { - if (str == null) - str = "null"; - int len = str.count; - ensureCapacity_unsynchronized(count + len); - str.getChars(0, len, value, count); - count += len; + super.append(str); return this; } @@ -383,15 +319,7 @@ public final class StringBuffer */ public synchronized StringBuffer append(StringBuffer stringBuffer) { - if (stringBuffer == null) - return append("null"); - synchronized (stringBuffer) - { - int len = stringBuffer.count; - ensureCapacity_unsynchronized(count + len); - VMSystem.arraycopy(stringBuffer.value, 0, value, count, len); - count += len; - } + super.append(stringBuffer); return this; } @@ -405,9 +333,10 @@ public final class StringBuffer * @throws NullPointerException if <code>str</code> is <code>null</code> * @see #append(char[], int, int) */ - public StringBuffer append(char[] data) + public synchronized StringBuffer append(char[] data) { - return append(data, 0, data.length); + super.append(data, 0, data.length); + return this; } /** @@ -426,30 +355,7 @@ public final class StringBuffer */ public synchronized StringBuffer append(char[] data, int offset, int count) { - if (offset < 0 || count < 0 || offset > data.length - count) - throw new StringIndexOutOfBoundsException(); - ensureCapacity_unsynchronized(this.count + count); - VMSystem.arraycopy(data, offset, value, this.count, count); - this.count += count; - return this; - } - - /** - * Append the code point to this <code>StringBuffer</code>. - * This is like #append(char), but will append two characters - * if a supplementary code point is given. - * - * @param code the code point to append - * @return this <code>StringBuffer</code> - * @see Character#toChars(int, char[], int) - * @since 1.5 - */ - public synchronized StringBuffer appendCodePoint(int code) - { - int len = Character.charCount(code); - ensureCapacity_unsynchronized(count + len); - Character.toChars(code, value, count); - count += len; + super.append(data, offset, count); return this; } @@ -462,9 +368,10 @@ public final class StringBuffer * @return this <code>StringBuffer</code> * @see String#valueOf(boolean) */ - public StringBuffer append(boolean bool) + public synchronized StringBuffer append(boolean bool) { - return append(bool ? "true" : "false"); + super.append(bool); + return this; } /** @@ -475,8 +382,7 @@ public final class StringBuffer */ public synchronized StringBuffer append(char ch) { - ensureCapacity_unsynchronized(count + 1); - value[count++] = ch; + super.append(ch); return this; } @@ -490,7 +396,8 @@ public final class StringBuffer */ public synchronized StringBuffer append(CharSequence seq) { - return append(seq, 0, seq.length()); + super.append(seq, 0, seq.length()); + return this; } /** @@ -506,14 +413,7 @@ public final class StringBuffer */ public synchronized StringBuffer append(CharSequence seq, int start, int end) { - if (seq == null) - return append("null"); - if (end - start > 0) - { - ensureCapacity_unsynchronized(count + end - start); - for (; start < end; ++start) - value[count++] = seq.charAt(start); - } + super.append(seq, start, end); return this; } @@ -527,9 +427,10 @@ public final class StringBuffer * @see String#valueOf(int) */ // This is native in libgcj, for efficiency. - public StringBuffer append(int inum) + public synchronized StringBuffer append(int inum) { - return append(String.valueOf(inum)); + super.append(inum); + return this; } /** @@ -541,9 +442,10 @@ public final class StringBuffer * @return this <code>StringBuffer</code> * @see String#valueOf(long) */ - public StringBuffer append(long lnum) + public synchronized StringBuffer append(long lnum) { - return append(Long.toString(lnum, 10)); + super.append(lnum); + return this; } /** @@ -555,9 +457,10 @@ public final class StringBuffer * @return this <code>StringBuffer</code> * @see String#valueOf(float) */ - public StringBuffer append(float fnum) + public synchronized StringBuffer append(float fnum) { - return append(Float.toString(fnum)); + super.append(fnum); + return this; } /** @@ -569,9 +472,26 @@ public final class StringBuffer * @return this <code>StringBuffer</code> * @see String#valueOf(double) */ - public StringBuffer append(double dnum) + public synchronized StringBuffer append(double dnum) { - return append(Double.toString(dnum)); + super.append(dnum); + return this; + } + + /** + * Append the code point to this <code>StringBuffer</code>. + * This is like #append(char), but will append two characters + * if a supplementary code point is given. + * + * @param code the code point to append + * @return this <code>StringBuffer</code> + * @see Character#toChars(int, char[], int) + * @since 1.5 + */ + public synchronized StringBuffer appendCodePoint(int code) + { + super.appendCodePoint(code); + return this; } /** @@ -587,15 +507,8 @@ public final class StringBuffer */ public synchronized StringBuffer delete(int start, int end) { - if (start < 0 || start > count || start > end) - throw new StringIndexOutOfBoundsException(start); - if (end > count) - end = count; // This will unshare if required. - ensureCapacity_unsynchronized(count); - if (count - end != 0) - VMSystem.arraycopy(value, end, value, start, count - end); - count -= end - start; + super.delete(start, end); return this; } @@ -607,9 +520,10 @@ public final class StringBuffer * @throws StringIndexOutOfBoundsException if index is out of bounds * @since 1.2 */ - public StringBuffer deleteCharAt(int index) + public synchronized StringBuffer deleteCharAt(int index) { - return delete(index, index + 1); + super.deleteCharAt(index); + return this; } /** @@ -628,19 +542,7 @@ public final class StringBuffer */ public synchronized StringBuffer replace(int start, int end, String str) { - if (start < 0 || start > count || start > end) - throw new StringIndexOutOfBoundsException(start); - - int len = str.count; - // Calculate the difference in 'count' after the replace. - int delta = len - (end > count ? count : end) + start; - ensureCapacity_unsynchronized(count + delta); - - if (delta != 0 && end < count) - VMSystem.arraycopy(value, end, value, end + delta, count - end); - - str.getChars(0, len, value, start); - count += delta; + super.replace(start, end, str); return this; } @@ -720,13 +622,7 @@ public final class StringBuffer public synchronized StringBuffer insert(int offset, char[] str, int str_offset, int len) { - if (offset < 0 || offset > count || len < 0 - || str_offset < 0 || str_offset > str.length - len) - throw new StringIndexOutOfBoundsException(); - ensureCapacity_unsynchronized(count + len); - VMSystem.arraycopy(value, offset, value, offset + len, count - offset); - VMSystem.arraycopy(str, str_offset, value, offset, len); - count += len; + super.insert(offset, str, str_offset, len); return this; } @@ -741,9 +637,10 @@ public final class StringBuffer * @exception StringIndexOutOfBoundsException if offset is out of bounds * @see String#valueOf(Object) */ - public StringBuffer insert(int offset, Object obj) + public synchronized StringBuffer insert(int offset, Object obj) { - return insert(offset, obj == null ? "null" : obj.toString()); + super.insert(offset, obj); + return this; } /** @@ -758,15 +655,7 @@ public final class StringBuffer */ public synchronized StringBuffer insert(int offset, String str) { - if (offset < 0 || offset > count) - throw new StringIndexOutOfBoundsException(offset); - if (str == null) - str = "null"; - int len = str.count; - ensureCapacity_unsynchronized(count + len); - VMSystem.arraycopy(value, offset, value, offset + len, count - offset); - str.getChars(0, len, value, offset); - count += len; + super.insert(offset, str); return this; } @@ -783,9 +672,8 @@ public final class StringBuffer */ public synchronized StringBuffer insert(int offset, CharSequence sequence) { - if (sequence == null) - sequence = "null"; - return insert(offset, sequence, 0, sequence.length()); + super.insert(offset, sequence); + return this; } /** @@ -805,16 +693,7 @@ public final class StringBuffer public synchronized StringBuffer insert(int offset, CharSequence sequence, int start, int end) { - if (sequence == null) - sequence = "null"; - if (start < 0 || end < 0 || start > end || end > sequence.length()) - throw new IndexOutOfBoundsException(); - int len = end - start; - ensureCapacity_unsynchronized(count + len); - VMSystem.arraycopy(value, offset, value, offset + len, count - offset); - for (int i = start; i < end; ++i) - value[offset++] = sequence.charAt(i); - count += len; + super.insert(offset, sequence, start, end); return this; } @@ -829,9 +708,10 @@ public final class StringBuffer * @throws StringIndexOutOfBoundsException if offset is out of bounds * @see #insert(int, char[], int, int) */ - public StringBuffer insert(int offset, char[] data) + public synchronized StringBuffer insert(int offset, char[] data) { - return insert(offset, data, 0, data.length); + super.insert(offset, data, 0, data.length); + return this; } /** @@ -845,9 +725,10 @@ public final class StringBuffer * @throws StringIndexOutOfBoundsException if offset is out of bounds * @see String#valueOf(boolean) */ - public StringBuffer insert(int offset, boolean bool) + public synchronized StringBuffer insert(int offset, boolean bool) { - return insert(offset, bool ? "true" : "false"); + super.insert(offset, bool); + return this; } /** @@ -860,12 +741,7 @@ public final class StringBuffer */ public synchronized StringBuffer insert(int offset, char ch) { - if (offset < 0 || offset > count) - throw new StringIndexOutOfBoundsException(offset); - ensureCapacity_unsynchronized(count + 1); - VMSystem.arraycopy(value, offset, value, offset + 1, count - offset); - value[offset] = ch; - count++; + super.insert(offset, ch); return this; } @@ -880,9 +756,10 @@ public final class StringBuffer * @throws StringIndexOutOfBoundsException if offset is out of bounds * @see String#valueOf(int) */ - public StringBuffer insert(int offset, int inum) + public synchronized StringBuffer insert(int offset, int inum) { - return insert(offset, String.valueOf(inum)); + super.insert(offset, inum); + return this; } /** @@ -896,9 +773,10 @@ public final class StringBuffer * @throws StringIndexOutOfBoundsException if offset is out of bounds * @see String#valueOf(long) */ - public StringBuffer insert(int offset, long lnum) + public synchronized StringBuffer insert(int offset, long lnum) { - return insert(offset, Long.toString(lnum, 10)); + super.insert(offset, lnum); + return this; } /** @@ -912,9 +790,10 @@ public final class StringBuffer * @throws StringIndexOutOfBoundsException if offset is out of bounds * @see String#valueOf(float) */ - public StringBuffer insert(int offset, float fnum) + public synchronized StringBuffer insert(int offset, float fnum) { - return insert(offset, Float.toString(fnum)); + super.insert(offset, fnum); + return this; } /** @@ -928,9 +807,10 @@ public final class StringBuffer * @throws StringIndexOutOfBoundsException if offset is out of bounds * @see String#valueOf(double) */ - public StringBuffer insert(int offset, double dnum) + public synchronized StringBuffer insert(int offset, double dnum) { - return insert(offset, Double.toString(dnum)); + super.insert(offset, dnum); + return this; } /** @@ -942,9 +822,9 @@ public final class StringBuffer * @see #indexOf(String, int) * @since 1.4 */ - public int indexOf(String str) + public synchronized int indexOf(String str) { - return indexOf(str, 0); + return super.indexOf(str, 0); } /** @@ -961,13 +841,7 @@ public final class StringBuffer */ public synchronized int indexOf(String str, int fromIndex) { - if (fromIndex < 0) - fromIndex = 0; - int limit = count - str.count; - for ( ; fromIndex <= limit; fromIndex++) - if (regionMatches(fromIndex, str)) - return fromIndex; - return -1; + return super.indexOf(str, fromIndex); } /** @@ -979,9 +853,9 @@ public final class StringBuffer * @see #lastIndexOf(String, int) * @since 1.4 */ - public int lastIndexOf(String str) + public synchronized int lastIndexOf(String str) { - return lastIndexOf(str, count - str.count); + return super.lastIndexOf(str, count - str.count); } /** @@ -998,11 +872,7 @@ public final class StringBuffer */ public synchronized int lastIndexOf(String str, int fromIndex) { - fromIndex = Math.min(fromIndex, count - str.count); - for ( ; fromIndex >= 0; fromIndex--) - if (regionMatches(fromIndex, str)) - return fromIndex; - return -1; + return super.lastIndexOf(str, fromIndex); } /** @@ -1013,14 +883,7 @@ public final class StringBuffer */ public synchronized StringBuffer reverse() { - // Call ensureCapacity to enforce copy-on-write. - ensureCapacity_unsynchronized(count); - for (int i = count >> 1, j = count - i; --i >= 0; ++j) - { - char c = value[i]; - value[i] = value[j]; - value[j] = c; - } + super.reverse(); return this; } @@ -1047,19 +910,7 @@ public final class StringBuffer */ public synchronized void trimToSize() { - int wouldSave = value.length - count; - // Some random heuristics: if we save less than 20 characters, who - // cares. - if (wouldSave < 20) - return; - // If we save more than 200 characters, shrink. - // If we save more than 1/4 of the buffer, shrink. - if (wouldSave > 200 || wouldSave * 4 > value.length) - { - char[] newValue = new char[count]; - VMSystem.arraycopy(value, 0, newValue, 0, count); - value = newValue; - } + super.trimToSize(); } /** @@ -1076,31 +927,7 @@ public final class StringBuffer */ public synchronized int codePointCount(int start, int end) { - if (start < 0 || end >= count || start > end) - throw new StringIndexOutOfBoundsException(); - - int count = 0; - while (start < end) - { - char base = value[start]; - if (base < Character.MIN_HIGH_SURROGATE - || base > Character.MAX_HIGH_SURROGATE - || start == end - || start == count - || value[start + 1] < Character.MIN_LOW_SURROGATE - || value[start + 1] > Character.MAX_LOW_SURROGATE) - { - // Nothing. - } - else - { - // Surrogate pair. - ++start; - } - ++start; - ++count; - } - return count; + return super.codePointCount(start, end); } /** @@ -1116,26 +943,7 @@ public final class StringBuffer */ public synchronized int offsetByCodePoints(int start, int codePoints) { - while (codePoints > 0) - { - char base = value[start]; - if (base < Character.MIN_HIGH_SURROGATE - || base > Character.MAX_HIGH_SURROGATE - || start == count - || value[start + 1] < Character.MIN_LOW_SURROGATE - || value[start + 1] > Character.MAX_LOW_SURROGATE) - { - // Nothing. - } - else - { - // Surrogate pair. - ++start; - } - ++start; - --codePoints; - } - return start; + return super.offsetByCodePoints(start, codePoints); } /** @@ -1147,7 +955,7 @@ public final class StringBuffer * @param minimumCapacity the minimum capacity * @see #ensureCapacity(int) */ - private void ensureCapacity_unsynchronized(int minimumCapacity) + void ensureCapacity_unsynchronized(int minimumCapacity) { if (shared || minimumCapacity > value.length) { @@ -1165,26 +973,4 @@ public final class StringBuffer } } - /** - * Predicate which determines if a substring of this matches another String - * starting at a specified offset for each String and continuing for a - * specified length. This is more efficient than creating a String to call - * indexOf on. - * - * @param toffset index to start comparison at for this String - * @param other non-null String to compare to region of this - * @return true if regions match, false otherwise - * @see #indexOf(String, int) - * @see #lastIndexOf(String, int) - * @see String#regionMatches(boolean, int, String, int, int) - */ - private boolean regionMatches(int toffset, String other) - { - int len = other.count; - int index = other.offset; - while (--len >= 0) - if (value[toffset++] != other.value[index++]) - return false; - return true; - } } diff --git a/libjava/classpath/java/lang/StringBuilder.java b/libjava/classpath/java/lang/StringBuilder.java index 95d04d1e766..aefe9272b6e 100644 --- a/libjava/classpath/java/lang/StringBuilder.java +++ b/libjava/classpath/java/lang/StringBuilder.java @@ -1,5 +1,5 @@ /* StringBuilder.java -- Unsynchronized growable strings - Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 + Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2008 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -75,6 +75,7 @@ import java.io.Serializable; * @since 1.5 */ public final class StringBuilder + extends AbstractStringBuffer implements Serializable, CharSequence, Appendable { // Implementation note: if you change this class, you usually will @@ -86,33 +87,11 @@ public final class StringBuilder private static final long serialVersionUID = 4383685877147921099L; /** - * Index of next available character (and thus the size of the current - * string contents). Note that this has permissions set this way so that - * String can get the value. - * - * @serial the number of characters in the buffer - */ - int count; - - /** - * The buffer. Note that this has permissions set this way so that String - * can get the value. - * - * @serial the buffer - */ - char[] value; - - /** - * The default capacity of a buffer. - */ - private static final int DEFAULT_CAPACITY = 16; - - /** * Create a new StringBuilder with default capacity 16. */ public StringBuilder() { - this(DEFAULT_CAPACITY); + super(); } /** @@ -124,7 +103,7 @@ public final class StringBuilder */ public StringBuilder(int capacity) { - value = new char[capacity]; + super(capacity); } /** @@ -137,10 +116,7 @@ public final class StringBuilder */ public StringBuilder(String str) { - // Unfortunately, because the size is 16 larger, we cannot share. - count = str.count; - value = new char[count + DEFAULT_CAPACITY]; - str.getChars(0, count, value, 0); + super(str); } /** @@ -154,11 +130,7 @@ public final class StringBuilder */ public StringBuilder(CharSequence seq) { - int len = seq.length(); - count = len <= 0 ? 0 : len; - value = new char[count + DEFAULT_CAPACITY]; - for (int i = 0; i < len; ++i) - value[i] = seq.charAt(i); + super(seq); } /** @@ -189,122 +161,6 @@ public final class StringBuilder } /** - * Increase the capacity of this <code>StringBuilder</code>. This will - * ensure that an expensive growing operation will not occur until - * <code>minimumCapacity</code> is reached. The buffer is grown to the - * larger of <code>minimumCapacity</code> and - * <code>capacity() * 2 + 2</code>, if it is not already large enough. - * - * @param minimumCapacity the new capacity - * @see #capacity() - */ - public void ensureCapacity(int minimumCapacity) - { - if (minimumCapacity > value.length) - { - int max = value.length * 2 + 2; - minimumCapacity = (minimumCapacity < max ? max : minimumCapacity); - char[] nb = new char[minimumCapacity]; - VMSystem.arraycopy(value, 0, nb, 0, count); - value = nb; - } - } - - /** - * Set the length of this StringBuilder. If the new length is greater than - * the current length, all the new characters are set to '\0'. If the new - * length is less than the current length, the first <code>newLength</code> - * characters of the old array will be preserved, and the remaining - * characters are truncated. - * - * @param newLength the new length - * @throws IndexOutOfBoundsException if the new length is negative - * (while unspecified, this is a StringIndexOutOfBoundsException) - * @see #length() - */ - public void setLength(int newLength) - { - if (newLength < 0) - throw new StringIndexOutOfBoundsException(newLength); - - int valueLength = value.length; - - /* Always call ensureCapacity in order to preserve copy-on-write - semantics. */ - ensureCapacity(newLength); - - if (newLength < valueLength) - { - /* If the StringBuilder's value just grew, then we know that - value is newly allocated and the region between count and - newLength is filled with '\0'. */ - count = newLength; - } - else - { - /* The StringBuilder's value doesn't need to grow. However, - we should clear out any cruft that may exist. */ - while (count < newLength) - value[count++] = '\0'; - } - } - - /** - * Get the character at the specified index. - * - * @param index the index of the character to get, starting at 0 - * @return the character at the specified index - * @throws IndexOutOfBoundsException if index is negative or >= length() - * (while unspecified, this is a StringIndexOutOfBoundsException) - */ - public char charAt(int index) - { - if (index < 0 || index >= count) - throw new StringIndexOutOfBoundsException(index); - return value[index]; - } - - /** - * Get the specified array of characters. <code>srcOffset - srcEnd</code> - * characters will be copied into the array you pass in. - * - * @param srcOffset the index to start copying from (inclusive) - * @param srcEnd the index to stop copying from (exclusive) - * @param dst the array to copy into - * @param dstOffset the index to start copying into - * @throws NullPointerException if dst is null - * @throws IndexOutOfBoundsException if any source or target indices are - * out of range (while unspecified, source problems cause a - * StringIndexOutOfBoundsException, and dest problems cause an - * ArrayIndexOutOfBoundsException) - * @see System#arraycopy(Object, int, Object, int, int) - */ - public void getChars(int srcOffset, int srcEnd, - char[] dst, int dstOffset) - { - if (srcOffset < 0 || srcEnd > count || srcEnd < srcOffset) - throw new StringIndexOutOfBoundsException(); - VMSystem.arraycopy(value, srcOffset, dst, dstOffset, srcEnd - srcOffset); - } - - /** - * Set the character at the specified index. - * - * @param index the index of the character to set starting at 0 - * @param ch the value to set that character to - * @throws IndexOutOfBoundsException if index is negative or >= length() - * (while unspecified, this is a StringIndexOutOfBoundsException) - */ - public void setCharAt(int index, char ch) - { - if (index < 0 || index >= count) - throw new StringIndexOutOfBoundsException(index); - // Call ensureCapacity to enforce copy-on-write. - ensureCapacity(count); - value[index] = ch; - } - - /** * Append the <code>String</code> value of the argument to this * <code>StringBuilder</code>. Uses <code>String.valueOf()</code> to convert * to <code>String</code>. @@ -316,7 +172,8 @@ public final class StringBuilder */ public StringBuilder append(Object obj) { - return append(obj == null ? "null" : obj.toString()); + super.append(obj); + return this; } /** @@ -328,12 +185,7 @@ public final class StringBuilder */ public StringBuilder append(String str) { - if (str == null) - str = "null"; - int len = str.count; - ensureCapacity(count + len); - str.getChars(0, len, value, count); - count += len; + super.append(str); return this; } @@ -348,15 +200,7 @@ public final class StringBuilder */ public StringBuilder append(StringBuffer stringBuffer) { - if (stringBuffer == null) - return append("null"); - synchronized (stringBuffer) - { - int len = stringBuffer.count; - ensureCapacity(count + len); - VMSystem.arraycopy(stringBuffer.value, 0, value, count, len); - count += len; - } + super.append(stringBuffer); return this; } @@ -372,7 +216,8 @@ public final class StringBuilder */ public StringBuilder append(char[] data) { - return append(data, 0, data.length); + super.append(data, 0, data.length); + return this; } /** @@ -391,11 +236,7 @@ public final class StringBuilder */ public StringBuilder append(char[] data, int offset, int count) { - if (offset < 0 || count < 0 || offset > data.length - count) - throw new StringIndexOutOfBoundsException(); - ensureCapacity(this.count + count); - VMSystem.arraycopy(data, offset, value, this.count, count); - this.count += count; + super.append(data, offset, count); return this; } @@ -410,7 +251,8 @@ public final class StringBuilder */ public StringBuilder append(boolean bool) { - return append(bool ? "true" : "false"); + super.append(bool); + return this; } /** @@ -421,8 +263,7 @@ public final class StringBuilder */ public StringBuilder append(char ch) { - ensureCapacity(count + 1); - value[count++] = ch; + super.append(ch); return this; } @@ -435,7 +276,8 @@ public final class StringBuilder */ public StringBuilder append(CharSequence seq) { - return append(seq, 0, seq.length()); + super.append(seq, 0, seq.length()); + return this; } /** @@ -451,33 +293,7 @@ public final class StringBuilder public StringBuilder append(CharSequence seq, int start, int end) { - if (seq == null) - return append("null"); - if (end - start > 0) - { - ensureCapacity(count + end - start); - for (; start < end; ++start) - value[count++] = seq.charAt(start); - } - return this; - } - - /** - * Append the code point to this <code>StringBuilder</code>. - * This is like #append(char), but will append two characters - * if a supplementary code point is given. - * - * @param code the code point to append - * @return this <code>StringBuilder</code> - * @see Character#toChars(int, char[], int) - * @since 1.5 - */ - public synchronized StringBuilder appendCodePoint(int code) - { - int len = Character.charCount(code); - ensureCapacity(count + len); - Character.toChars(code, value, count); - count += len; + super.append(seq, start, end); return this; } @@ -493,7 +309,8 @@ public final class StringBuilder // This is native in libgcj, for efficiency. public StringBuilder append(int inum) { - return append(String.valueOf(inum)); + super.append(inum); + return this; } /** @@ -507,7 +324,8 @@ public final class StringBuilder */ public StringBuilder append(long lnum) { - return append(Long.toString(lnum, 10)); + super.append(lnum); + return this; } /** @@ -521,7 +339,8 @@ public final class StringBuilder */ public StringBuilder append(float fnum) { - return append(Float.toString(fnum)); + super.append(fnum); + return this; } /** @@ -535,7 +354,24 @@ public final class StringBuilder */ public StringBuilder append(double dnum) { - return append(Double.toString(dnum)); + super.append(dnum); + return this; + } + + /** + * Append the code point to this <code>StringBuilder</code>. + * This is like #append(char), but will append two characters + * if a supplementary code point is given. + * + * @param code the code point to append + * @return this <code>StringBuilder</code> + * @see Character#toChars(int, char[], int) + * @since 1.5 + */ + public StringBuilder appendCodePoint(int code) + { + super.appendCodePoint(code); + return this; } /** @@ -550,15 +386,7 @@ public final class StringBuilder */ public StringBuilder delete(int start, int end) { - if (start < 0 || start > count || start > end) - throw new StringIndexOutOfBoundsException(start); - if (end > count) - end = count; - // This will unshare if required. - ensureCapacity(count); - if (count - end != 0) - VMSystem.arraycopy(value, end, value, start, count - end); - count -= end - start; + super.delete(start, end); return this; } @@ -571,7 +399,8 @@ public final class StringBuilder */ public StringBuilder deleteCharAt(int index) { - return delete(index, index + 1); + super.deleteCharAt(index); + return this; } /** @@ -589,19 +418,7 @@ public final class StringBuilder */ public StringBuilder replace(int start, int end, String str) { - if (start < 0 || start > count || start > end) - throw new StringIndexOutOfBoundsException(start); - - int len = str.count; - // Calculate the difference in 'count' after the replace. - int delta = len - (end > count ? count : end) + start; - ensureCapacity(count + delta); - - if (delta != 0 && end < count) - VMSystem.arraycopy(value, end, value, end + delta, count - end); - - str.getChars(0, len, value, start); - count += delta; + super.replace(start, end, str); return this; } @@ -672,13 +489,7 @@ public final class StringBuilder public StringBuilder insert(int offset, char[] str, int str_offset, int len) { - if (offset < 0 || offset > count || len < 0 - || str_offset < 0 || str_offset > str.length - len) - throw new StringIndexOutOfBoundsException(); - ensureCapacity(count + len); - VMSystem.arraycopy(value, offset, value, offset + len, count - offset); - VMSystem.arraycopy(str, str_offset, value, offset, len); - count += len; + super.insert(offset, str, str_offset, len); return this; } @@ -695,7 +506,8 @@ public final class StringBuilder */ public StringBuilder insert(int offset, Object obj) { - return insert(offset, obj == null ? "null" : obj.toString()); + super.insert(offset, obj); + return this; } /** @@ -710,15 +522,7 @@ public final class StringBuilder */ public StringBuilder insert(int offset, String str) { - if (offset < 0 || offset > count) - throw new StringIndexOutOfBoundsException(offset); - if (str == null) - str = "null"; - int len = str.count; - ensureCapacity(count + len); - VMSystem.arraycopy(value, offset, value, offset + len, count - offset); - str.getChars(0, len, value, offset); - count += len; + super.insert(offset, str); return this; } @@ -732,11 +536,10 @@ public final class StringBuilder * @return this <code>StringBuilder</code> * @throws IndexOutOfBoundsException if offset is out of bounds */ - public synchronized StringBuilder insert(int offset, CharSequence sequence) + public StringBuilder insert(int offset, CharSequence sequence) { - if (sequence == null) - sequence = "null"; - return insert(offset, sequence, 0, sequence.length()); + super.insert(offset, sequence); + return this; } /** @@ -752,19 +555,10 @@ public final class StringBuilder * @throws IndexOutOfBoundsException if offset, start, * or end are out of bounds */ - public synchronized StringBuilder insert(int offset, CharSequence sequence, - int start, int end) + public StringBuilder insert(int offset, CharSequence sequence, + int start, int end) { - if (sequence == null) - sequence = "null"; - if (start < 0 || end < 0 || start > end || end > sequence.length()) - throw new IndexOutOfBoundsException(); - int len = end - start; - ensureCapacity(count + len); - VMSystem.arraycopy(value, offset, value, offset + len, count - offset); - for (int i = start; i < end; ++i) - value[offset++] = sequence.charAt(i); - count += len; + super.insert(offset, sequence, start, end); return this; } @@ -781,7 +575,8 @@ public final class StringBuilder */ public StringBuilder insert(int offset, char[] data) { - return insert(offset, data, 0, data.length); + super.insert(offset, data); + return this; } /** @@ -797,7 +592,8 @@ public final class StringBuilder */ public StringBuilder insert(int offset, boolean bool) { - return insert(offset, bool ? "true" : "false"); + super.insert(offset, bool); + return this; } /** @@ -810,12 +606,7 @@ public final class StringBuilder */ public StringBuilder insert(int offset, char ch) { - if (offset < 0 || offset > count) - throw new StringIndexOutOfBoundsException(offset); - ensureCapacity(count + 1); - VMSystem.arraycopy(value, offset, value, offset + 1, count - offset); - value[offset] = ch; - count++; + super.insert(offset, ch); return this; } @@ -832,7 +623,8 @@ public final class StringBuilder */ public StringBuilder insert(int offset, int inum) { - return insert(offset, String.valueOf(inum)); + super.insert(offset, inum); + return this; } /** @@ -848,7 +640,8 @@ public final class StringBuilder */ public StringBuilder insert(int offset, long lnum) { - return insert(offset, Long.toString(lnum, 10)); + super.insert(offset, lnum); + return this; } /** @@ -864,7 +657,8 @@ public final class StringBuilder */ public StringBuilder insert(int offset, float fnum) { - return insert(offset, Float.toString(fnum)); + super.insert(offset, fnum); + return this; } /** @@ -880,75 +674,8 @@ public final class StringBuilder */ public StringBuilder insert(int offset, double dnum) { - return insert(offset, Double.toString(dnum)); - } - - /** - * Finds the first instance of a substring in this StringBuilder. - * - * @param str String to find - * @return location (base 0) of the String, or -1 if not found - * @throws NullPointerException if str is null - * @see #indexOf(String, int) - */ - public int indexOf(String str) - { - return indexOf(str, 0); - } - - /** - * Finds the first instance of a String in this StringBuilder, starting at - * a given index. If starting index is less than 0, the search starts at - * the beginning of this String. If the starting index is greater than the - * length of this String, or the substring is not found, -1 is returned. - * - * @param str String to find - * @param fromIndex index to start the search - * @return location (base 0) of the String, or -1 if not found - * @throws NullPointerException if str is null - */ - public int indexOf(String str, int fromIndex) - { - if (fromIndex < 0) - fromIndex = 0; - int limit = count - str.count; - for ( ; fromIndex <= limit; fromIndex++) - if (regionMatches(fromIndex, str)) - return fromIndex; - return -1; - } - - /** - * Finds the last instance of a substring in this StringBuilder. - * - * @param str String to find - * @return location (base 0) of the String, or -1 if not found - * @throws NullPointerException if str is null - * @see #lastIndexOf(String, int) - */ - public int lastIndexOf(String str) - { - return lastIndexOf(str, count - str.count); - } - - /** - * Finds the last instance of a String in this StringBuilder, starting at a - * given index. If starting index is greater than the maximum valid index, - * then the search begins at the end of this String. If the starting index - * is less than zero, or the substring is not found, -1 is returned. - * - * @param str String to find - * @param fromIndex index to start the search - * @return location (base 0) of the String, or -1 if not found - * @throws NullPointerException if str is null - */ - public int lastIndexOf(String str, int fromIndex) - { - fromIndex = Math.min(fromIndex, count - str.count); - for ( ; fromIndex >= 0; fromIndex--) - if (regionMatches(fromIndex, str)) - return fromIndex; - return -1; + super.insert(offset, dnum); + return this; } /** @@ -959,14 +686,7 @@ public final class StringBuilder */ public StringBuilder reverse() { - // Call ensureCapacity to enforce copy-on-write. - ensureCapacity(count); - for (int i = count >> 1, j = count - i; --i >= 0; ++j) - { - char c = value[i]; - value[i] = value[j]; - value[j] = c; - } + super.reverse(); return this; } @@ -983,87 +703,4 @@ public final class StringBuilder return new String(this); } - /** - * Predicate which determines if a substring of this matches another String - * starting at a specified offset for each String and continuing for a - * specified length. This is more efficient than creating a String to call - * indexOf on. - * - * @param toffset index to start comparison at for this String - * @param other non-null String to compare to region of this - * @return true if regions match, false otherwise - * @see #indexOf(String, int) - * @see #lastIndexOf(String, int) - * @see String#regionMatches(boolean, int, String, int, int) - */ - private boolean regionMatches(int toffset, String other) - { - int len = other.count; - int index = other.offset; - while (--len >= 0) - if (value[toffset++] != other.value[index++]) - return false; - return true; - } - - /** - * Get the code point at the specified index. This is like #charAt(int), - * but if the character is the start of a surrogate pair, and the - * following character completes the pair, then the corresponding - * supplementary code point is returned. - * @param index the index of the codepoint to get, starting at 0 - * @return the codepoint at the specified index - * @throws IndexOutOfBoundsException if index is negative or >= length() - * @since 1.5 - */ - public int codePointAt(int index) - { - return Character.codePointAt(value, index, count); - } - - /** - * Get the code point before the specified index. This is like - * #codePointAt(int), but checks the characters at <code>index-1</code> and - * <code>index-2</code> to see if they form a supplementary code point. - * @param index the index just past the codepoint to get, starting at 0 - * @return the codepoint at the specified index - * @throws IndexOutOfBoundsException if index is negative or >= length() - * @since 1.5 - */ - public int codePointBefore(int index) - { - // Character.codePointBefore() doesn't perform this check. We - // could use the CharSequence overload, but this is just as easy. - if (index >= count) - throw new IndexOutOfBoundsException(); - return Character.codePointBefore(value, index, 1); - } - - /** - * Returns the number of Unicode code points in the specified sub sequence. - * Surrogate pairs count as one code point. - * @param beginIndex the start of the subarray - * @param endIndex the index after the last char in the subarray - * @return the number of code points - * @throws IndexOutOfBoundsException if beginIndex is less than zero or - * greater than endIndex or if endIndex is greater than the length of this - * StringBuilder - */ - public int codePointCount(int beginIndex,int endIndex) - { - if (beginIndex < 0 || beginIndex > endIndex || endIndex > count) - throw new IndexOutOfBoundsException("invalid indices: " + beginIndex - + ", " + endIndex); - return Character.codePointCount(value, beginIndex, endIndex - beginIndex); - } - - public void trimToSize() - { - if (count < value.length) - { - char[] newValue = new char[count]; - VMSystem.arraycopy(value, 0, newValue, 0, count); - value = newValue; - } - } } diff --git a/libjava/classpath/java/lang/Thread.java b/libjava/classpath/java/lang/Thread.java index 01b380b67b5..82e72618780 100644 --- a/libjava/classpath/java/lang/Thread.java +++ b/libjava/classpath/java/lang/Thread.java @@ -159,7 +159,7 @@ public class Thread implements Runnable /** Thread local storage. Package accessible for use by * InheritableThreadLocal. */ - WeakIdentityHashMap locals; + final ThreadLocalMap locals; /** The uncaught exception handler. */ UncaughtExceptionHandler exceptionHandler; @@ -367,6 +367,7 @@ public class Thread implements Runnable this.name = name.toString(); this.runnable = target; this.stacksize = size; + this.locals = new ThreadLocalMap(); synchronized (Thread.class) { @@ -398,6 +399,7 @@ public class Thread implements Runnable */ Thread(VMThread vmThread, String name, int priority, boolean daemon) { + this.locals = new ThreadLocalMap(); this.vmThread = vmThread; this.runnable = null; if (name == null) @@ -1063,21 +1065,15 @@ public class Thread implements Runnable { group.removeThread(this); vmThread = null; - locals = null; + locals.clear(); } /** * Returns the map used by ThreadLocal to store the thread local values. */ - static Map getThreadLocals() + static ThreadLocalMap getThreadLocals() { - Thread thread = currentThread(); - Map locals = thread.locals; - if (locals == null) - { - locals = thread.locals = new WeakIdentityHashMap(); - } - return locals; + return currentThread().locals; } /** diff --git a/libjava/classpath/java/lang/ThreadLocal.java b/libjava/classpath/java/lang/ThreadLocal.java index 6c4ba176a41..14778c65c2f 100644 --- a/libjava/classpath/java/lang/ThreadLocal.java +++ b/libjava/classpath/java/lang/ThreadLocal.java @@ -37,9 +37,6 @@ exception statement from your version. */ package java.lang; -import java.util.Map; - - /** * ThreadLocal objects have a different state associated with every * Thread that accesses them. Every access to the ThreadLocal object @@ -93,13 +90,31 @@ public class ThreadLocal<T> * user. Do not expose this to the public. Package visible for use by * InheritableThreadLocal */ - static final Object sentinel = new Object(); + static final Object notFound = new Object(); + + /** + * The base for the computation of the next hash for a thread local. + */ + private static int nextHashBase = 1; + + /** + * Allocate a new hash. + */ + private synchronized int computeNextHash() { + return nextHashBase++ * 6709; + } + + /** + * Hash code computed for ThreadLocalMap + */ + final int fastHash; /** * Creates a ThreadLocal object without associating any value to it yet. */ public ThreadLocal() { + fastHash = computeNextHash(); } /** @@ -125,16 +140,16 @@ public class ThreadLocal<T> */ public T get() { - Map<ThreadLocal<T>,T> map = (Map<ThreadLocal<T>,T>) Thread.getThreadLocals(); + ThreadLocalMap map = Thread.getThreadLocals(); // Note that we don't have to synchronize, as only this thread will // ever modify the map. - T value = map.get(this); - if (value == null) + T value = (T) map.get(this); + if (value == notFound) { value = initialValue(); - map.put(this, (T) (value == null ? sentinel : value)); + map.set(this, value); } - return value == (T) sentinel ? null : value; + return value; } /** @@ -147,10 +162,10 @@ public class ThreadLocal<T> */ public void set(T value) { - Map map = Thread.getThreadLocals(); + ThreadLocalMap map = Thread.getThreadLocals(); // Note that we don't have to synchronize, as only this thread will // ever modify the map. - map.put(this, value == null ? sentinel : value); + map.set(this, value); } /** @@ -160,7 +175,7 @@ public class ThreadLocal<T> */ public void remove() { - Map map = Thread.getThreadLocals(); + ThreadLocalMap map = Thread.getThreadLocals(); map.remove(this); } } diff --git a/libjava/classpath/java/lang/ThreadLocalMap.java b/libjava/classpath/java/lang/ThreadLocalMap.java new file mode 100644 index 00000000000..7f67b131183 --- /dev/null +++ b/libjava/classpath/java/lang/ThreadLocalMap.java @@ -0,0 +1,325 @@ +/* ThreadLocal -- a variable with a unique value per thread + Copyright (C) 2000, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + +package java.lang; + +import java.lang.ref.WeakReference; + +/** + * ThreadLocalMap is the basic storage for the map of ThreadLocal instance + * to a thread's current value. + * + * Some applications really work out ThreadLocals, leading to this + * optimized implementation. + */ +final class ThreadLocalMap +{ + /** + * The log (base 2) of the initial size of the map + */ + private static final int LOG_INITIAL_SIZE = 3; + + /** + * The maximum occupancy rate (after which we grow) + */ + private static final float MAX_OCCUPANCY = 0.7f; + + /** + * The target occupancy rate. + */ + private static final float TARGET_OCCUPANCY = 0.5f; + + /** + * The deleted entry sentinel value. + */ + private static final Entry deletedEntry = new Entry(null); + + /** + * Constructor + */ + ThreadLocalMap() + { + /* Dummy value to ensure fast path can be optimized */ + entries = new Entry[1]; + hashMask = 0; + count = 0; + } + + /** + * The map entries + */ + private Entry[] entries; + + /** + * Used for start index computation + */ + private int hashMask; + + /** + * The number of entries currently in the map + */ + private int count; + + /** + * Create or grow the table to the specified size. The size must be a + * power of two for the efficient mask/hash computation. + * + * @param newSize The new table size. + */ + private void newEntryArray(int newSize) + { + int mask = newSize - 1; + Entry[] oldEntries = this.entries; + this.entries = new Entry[newSize]; + this.hashMask = mask; + + /* Copy old entries to new table */ + count = 0; + if (oldEntries != null) + { + for(Entry e: oldEntries) + { + if (e != null) + { + ThreadLocal<?> key = e.get(); + if (e != deletedEntry && key != null) + { + for(int i = key.fastHash & mask;; i = (i + 1) & mask) + { + if (entries[i] == null) + { + entries[i] = e; + count++; + break; + } + } + } + } + } + } + } + + /** + * We have run out of space in our locals. We use this as the + * trigger to attempt to find unused slots as ThreadLocals have + * died. If we recover any slots this way then we do not grow. + */ + private void overflow() + { + /* First 'actual' use */ + if (entries.length == 1) + { + newEntryArray(1 << LOG_INITIAL_SIZE); + return; + } + + /* Attempt to recover unused slots */ + int deleted = 0; + for(int i=0; i < entries.length; i++) + { + Entry e = entries[i]; + if (e != null) + { + if (e == deletedEntry) + { + deleted++; + } + else if (e.get() == null) + { + entries[i] = deletedEntry; + deleted++; + } + } + } + + if ((count-deleted) <= (TARGET_OCCUPANCY * entries.length)) + { + /* We currently rehash by simple reallocating into a same-sized table. + * An alternative would be to implement a clever hashing algorithm but + * as this happens infrequently this seems preferred */ + newEntryArray(entries.length); + return; + } + + /* Double the size */ + newEntryArray(entries.length << 1); + } + + /** + * This is the class that is used to refer to a thread local weakly. + * + * As we want to minimize indirections we extend WeakReference. + */ + static final class Entry extends WeakReference<ThreadLocal<?>> { + /** + * The value stored in this slot + */ + Object value; + + /** + * Constructor + */ + Entry(ThreadLocal<?> threadLocal) { + super(threadLocal); + } + } + + /** + * Gets the value associated with the ThreadLocal object for the currently + * executing Thread. If this is the first time the current thread has called + * get(), and it has not already called set(), the sentinel value is returned. + * + * @return the value of the variable in this thread, or sentinel if not present. + */ + public Object get(ThreadLocal<?> key) + { + int mask = this.hashMask; + for(int i = key.fastHash & mask;; i = (i + 1) & mask) { + Entry e = entries[i]; + if (e != null) { + if (e.get() == key) { + return e.value; + } + } else { + return ThreadLocal.sentinel; + } + } + } + + /** + * Sets the value associated with the ThreadLocal object for the currently + * executing Thread. This overrides any existing value associated with the + * current Thread and prevents <code>initialValue()</code> from being + * called if this is the first access to this ThreadLocal in this Thread. + * + * @param value the value to set this thread's view of the variable to + */ + public void set(ThreadLocal<?> key, Object value) + { + /* Overflow ? */ + if ((count+1) >= (MAX_OCCUPANCY * entries.length)) + { + overflow(); + } + + /* Set the entry */ + int mask = this.hashMask; + for(int i = key.fastHash & mask;; i = (i + 1) & mask) + { + Entry e = entries[i]; + if (e == null || e == deletedEntry) + { + /* Create entry */ + if (e == null) count++; + entries[i] = e = new Entry(key); + e.value = value; + return; + } + else + { + ThreadLocal<?> entryKey = e.get(); + if (entryKey == null) + { + entries[i] = deletedEntry; + } + else if (entryKey == key) + { + /* Update entry */ + e.value = value; + return; + } + } + } + } + + /** + * Removes the value associated with the ThreadLocal object for the + * currently executing Thread. + * @since 1.5 + */ + public void remove(ThreadLocal<?> key) + { + int mask = this.hashMask; + for(int i = key.fastHash & mask;; i = (i + 1) & mask) + { + Entry e = entries[i]; + if (e != null) + { + ThreadLocal<?> entryKey = e.get(); + if (entryKey != key) + { + if (entryKey == null) { + entries[i] = deletedEntry; + } + continue; + } + else + { + /* Remove from the table */ + entries[i] = deletedEntry; + } + } + return; + } + } + + /** + * Clear out the map. Done once during thread death. + */ + void clear() { + entries = null; + } + + /** + * Inherit all the InheritableThreadLocal instances from the given parent. + * + * @param parentMap The map to inherit from. + */ + public void inherit(ThreadLocalMap parentMap) { + for(Entry e: parentMap.entries) + { + if (e != null && e != deletedEntry) + { + ThreadLocal<?> key = e.get(); + if (key instanceof InheritableThreadLocal) + { + set(key, ((InheritableThreadLocal)key).childValue(e.value)); + } + } + } + } +} diff --git a/libjava/classpath/java/lang/Throwable.java b/libjava/classpath/java/lang/Throwable.java index 72f9e7f520b..f74851f0b1b 100644 --- a/libjava/classpath/java/lang/Throwable.java +++ b/libjava/classpath/java/lang/Throwable.java @@ -39,6 +39,8 @@ package java.lang; import gnu.classpath.SystemProperties; +import gnu.java.lang.CPStringBuilder; + import java.io.PrintStream; import java.io.PrintWriter; import java.io.Serializable; @@ -411,7 +413,7 @@ public class Throwable implements Serializable // different threads to get mixed up when written to the same PrintWriter. private String stackTraceString() { - StringBuilder sb = new StringBuilder(); + CPStringBuilder sb = new CPStringBuilder(); // Main stacktrace StackTraceElement[] stack = getStackTrace(); @@ -455,7 +457,7 @@ public class Throwable implements Serializable // Adds to the given StringBuffer a line containing the name and // all stacktrace elements minus the last equal ones. - private static void stackTraceStringBuffer(StringBuilder sb, String name, + private static void stackTraceStringBuffer(CPStringBuilder sb, String name, StackTraceElement[] stack, int equal) { String nl = StaticData.nl; diff --git a/libjava/classpath/java/lang/reflect/AccessibleObject.java b/libjava/classpath/java/lang/reflect/AccessibleObject.java index fd46a53dc8c..328f81d7933 100644 --- a/libjava/classpath/java/lang/reflect/AccessibleObject.java +++ b/libjava/classpath/java/lang/reflect/AccessibleObject.java @@ -160,21 +160,72 @@ public class AccessibleObject this.flag = flag; } + /** + * <p> + * Returns the element's annotation for the specified annotation type, + * or <code>null</code> if no such annotation exists. + * </p> + * <p> + * <strong>This method must be overridden by subclasses to provide + * appropriate behaviour.</strong> + * </p> + * + * @param annotationClass the type of annotation to look for. + * @return this element's annotation for the specified type, or + * <code>null</code> if no such annotation exists. + * @throws NullPointerException if the annotation class is <code>null</code>. + */ public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { throw new AssertionError("Subclass must override this method"); } + /** + * Returns all annotations associated with the element. If there are + * no annotations associated with the element, then a zero-length array + * will be returned. The returned array may be modified by the client + * code, but this will have no effect on the annotation content of the + * element, and hence no effect on the return value of this method for + * future callers. + * + * @return this element's annotations. + */ public Annotation[] getAnnotations() { return getDeclaredAnnotations(); } + /** + * <p> + * Returns all annotations directly defined by the element. If there are + * no annotations directly associated with the element, then a zero-length + * array will be returned. The returned array may be modified by the client + * code, but this will have no effect on the annotation content of this + * class, and hence no effect on the return value of this method for + * future callers. + * </p> + * <p> + * <strong>This method must be overridden by subclasses to provide + * appropriate behaviour.</strong> + * </p> + * + * @return the annotations directly defined by the element. + * @since 1.5 + */ public Annotation[] getDeclaredAnnotations() { throw new AssertionError("Subclass must override this method"); } + /** + * Returns true if an annotation for the specified type is associated + * with the element. This is primarily a short-hand for using marker + * annotations. + * + * @param annotationClass the type of annotation to look for. + * @return true if an annotation exists for the specified type. + * @since 1.5 + */ public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) { return getAnnotation(annotationClass) != null; diff --git a/libjava/classpath/java/lang/reflect/Constructor.java b/libjava/classpath/java/lang/reflect/Constructor.java new file mode 100644 index 00000000000..d9b7e831216 --- /dev/null +++ b/libjava/classpath/java/lang/reflect/Constructor.java @@ -0,0 +1,453 @@ +/* java.lang.reflect.Constructor - reflection of Java constructors + Copyright (C) 1998, 2001, 2004, 2005 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package java.lang.reflect; + +import gnu.java.lang.ClassHelper; +import gnu.java.lang.CPStringBuilder; + +import gnu.java.lang.reflect.MethodSignatureParser; + +import java.lang.annotation.Annotation; + +/** + * The Constructor class represents a constructor of a class. It also allows + * dynamic creation of an object, via reflection. Invocation on Constructor + * objects knows how to do widening conversions, but throws + * {@link IllegalArgumentException} if a narrowing conversion would be + * necessary. You can query for information on this Constructor regardless + * of location, but construction access may be limited by Java language + * access controls. If you can't do it in the compiler, you can't normally + * do it here either.<p> + * + * <B>Note:</B> This class returns and accepts types as Classes, even + * primitive types; there are Class types defined that represent each + * different primitive type. They are <code>java.lang.Boolean.TYPE, + * java.lang.Byte.TYPE,</code>, also available as <code>boolean.class, + * byte.class</code>, etc. These are not to be confused with the + * classes <code>java.lang.Boolean, java.lang.Byte</code>, etc., which are + * real classes.<p> + * + * Also note that this is not a serializable class. It is entirely feasible + * to make it serializable using the Externalizable interface, but this is + * on Sun, not me. + * + * @author John Keiser + * @author Eric Blake <ebb9@email.byu.edu> + * @see Member + * @see Class + * @see java.lang.Class#getConstructor(Class[]) + * @see java.lang.Class#getDeclaredConstructor(Class[]) + * @see java.lang.Class#getConstructors() + * @see java.lang.Class#getDeclaredConstructors() + * @since 1.1 + * @status updated to 1.4 + */ +public final class Constructor<T> + extends AccessibleObject + implements GenericDeclaration, Member +{ + private static final int CONSTRUCTOR_MODIFIERS + = Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC; + + private MethodSignatureParser p; + + VMConstructor cons; + + /** + * This class is uninstantiable outside this package. + */ + Constructor(VMConstructor cons) + { + this.cons = cons; + cons.cons = this; + } + + private Constructor() + { + } + + /** + * Gets the class that declared this constructor. + * @return the class that declared this member + */ + public Class<T> getDeclaringClass() + { + // Inescapable as the VM layer is 1.4 based. + @SuppressWarnings("unchecked") + Class<T> declClass = (Class<T>) cons.getDeclaringClass(); + return declClass; + } + + /** + * Gets the name of this constructor (the non-qualified name of the class + * it was declared in). + * @return the name of this constructor + */ + public String getName() + { + return cons.getDeclaringClass().getName(); + } + + /** + * Gets the modifiers this constructor uses. Use the <code>Modifier</code> + * class to interpret the values. A constructor can only have a subset of the + * following modifiers: public, private, protected. + * + * @return an integer representing the modifiers to this Member + * @see Modifier + */ + public int getModifiers() + { + return cons.getModifiersInternal() & CONSTRUCTOR_MODIFIERS; + } + + /** + * Return true if this constructor is synthetic, false otherwise. + * A synthetic member is one which is created by the compiler, + * and which does not appear in the user's source code. + * @since 1.5 + */ + public boolean isSynthetic() + { + return (cons.getModifiersInternal() & Modifier.SYNTHETIC) != 0; + } + + /** + * Return true if this is a varargs constructor, that is if + * the constructor takes a variable number of arguments. + * @since 1.5 + */ + public boolean isVarArgs() + { + return (cons.getModifiersInternal() & Modifier.VARARGS) != 0; + } + + /** + * Get the parameter list for this constructor, in declaration order. If the + * constructor takes no parameters, returns a 0-length array (not null). + * + * @return a list of the types of the constructor's parameters + */ + public Class<?>[] getParameterTypes() + { + return (Class<?>[]) cons.getParameterTypes(); + } + + /** + * Get the exception types this constructor says it throws, in no particular + * order. If the constructor has no throws clause, returns a 0-length array + * (not null). + * + * @return a list of the types in the constructor's throws clause + */ + public Class<?>[] getExceptionTypes() + { + return (Class<?>[]) cons.getExceptionTypes(); + } + + /** + * Compare two objects to see if they are semantically equivalent. + * Two Constructors are semantically equivalent if they have the same + * declaring class and the same parameter list. This ignores different + * exception clauses, but since you can't create a Method except through the + * VM, this is just the == relation. + * + * @param o the object to compare to + * @return <code>true</code> if they are equal; <code>false</code> if not. + */ + public boolean equals(Object o) + { + return cons.equals(o); + } + + /** + * Get the hash code for the Constructor. The Constructor hash code is the + * hash code of the declaring class's name. + * + * @return the hash code for the object + */ + public int hashCode() + { + return getName().hashCode(); + } + + /** + * Get a String representation of the Constructor. A Constructor's String + * representation is "<modifier> <classname>(<paramtypes>) + * throws <exceptions>", where everything after ')' is omitted if + * there are no exceptions.<br> Example: + * <code>public java.io.FileInputStream(java.lang.Runnable) + * throws java.io.FileNotFoundException</code> + * + * @return the String representation of the Constructor + */ + public String toString() + { + // 128 is a reasonable buffer initial size for constructor + CPStringBuilder sb = new CPStringBuilder(128); + Modifier.toString(getModifiers(), sb).append(' '); + sb.append(getDeclaringClass().getName()).append('('); + Class[] c = getParameterTypes(); + if (c.length > 0) + { + sb.append(ClassHelper.getUserName(c[0])); + for (int i = 1; i < c.length; i++) + sb.append(',').append(ClassHelper.getUserName(c[i])); + } + sb.append(')'); + c = getExceptionTypes(); + if (c.length > 0) + { + sb.append(" throws ").append(c[0].getName()); + for (int i = 1; i < c.length; i++) + sb.append(',').append(c[i].getName()); + } + return sb.toString(); + } + + static <X extends GenericDeclaration> + void addTypeParameters(CPStringBuilder sb, TypeVariable<X>[] typeArgs) + { + if (typeArgs.length == 0) + return; + sb.append('<'); + for (int i = 0; i < typeArgs.length; ++i) + { + if (i > 0) + sb.append(','); + sb.append(typeArgs[i]); + } + sb.append("> "); + } + + public String toGenericString() + { + CPStringBuilder sb = new CPStringBuilder(128); + Modifier.toString(getModifiers(), sb).append(' '); + addTypeParameters(sb, getTypeParameters()); + sb.append(getDeclaringClass().getName()).append('('); + Type[] types = getGenericParameterTypes(); + if (types.length > 0) + { + sb.append(types[0]); + for (int i = 1; i < types.length; ++i) + sb.append(',').append(types[i]); + } + sb.append(')'); + types = getGenericExceptionTypes(); + if (types.length > 0) + { + sb.append(" throws ").append(types[0]); + for (int i = 1; i < types.length; i++) + sb.append(',').append(types[i]); + } + return sb.toString(); + } + + /** + * Create a new instance by invoking the constructor. Arguments are + * automatically unwrapped and widened, if needed.<p> + * + * If this class is abstract, you will get an + * <code>InstantiationException</code>. If the constructor takes 0 + * arguments, you may use null or a 0-length array for <code>args</code>.<p> + * + * If this Constructor enforces access control, your runtime context is + * evaluated, and you may have an <code>IllegalAccessException</code> if + * you could not create this object in similar compiled code. If the class + * is uninitialized, you trigger class initialization, which may end in a + * <code>ExceptionInInitializerError</code>.<p> + * + * Then, the constructor is invoked. If it completes normally, the return + * value will be the new object. If it completes abruptly, the exception is + * wrapped in an <code>InvocationTargetException</code>. + * + * @param args the arguments to the constructor + * @return the newly created object + * @throws IllegalAccessException if the constructor could not normally be + * called by the Java code (i.e. it is not public) + * @throws IllegalArgumentException if the number of arguments is incorrect; + * or if the arguments types are wrong even with a widening + * conversion + * @throws InstantiationException if the class is abstract + * @throws InvocationTargetException if the constructor throws an exception + * @throws ExceptionInInitializerError if construction triggered class + * initialization, which then failed + */ + public T newInstance(Object... args) + throws InstantiationException, IllegalAccessException, + InvocationTargetException + { + // Inescapable as the VM layer is 1.4 based. + @SuppressWarnings("unchecked") + T ins = (T) cons.construct(args); + return ins; + } + + /** + * Returns an array of <code>TypeVariable</code> objects that represents + * the type variables declared by this constructor, in declaration order. + * An array of size zero is returned if this constructor has no type + * variables. + * + * @return the type variables associated with this constructor. + * @throws GenericSignatureFormatError if the generic signature does + * not conform to the format specified in the Virtual Machine + * specification, version 3. + * @since 1.5 + */ + public TypeVariable<Constructor<T>>[] getTypeParameters() + { + if (p == null) + { + String sig = cons.getSignature(); + if (sig == null) + return new TypeVariable[0]; + p = new MethodSignatureParser(this, sig); + } + return p.getTypeParameters(); + } + + /** + * Returns an array of <code>Type</code> objects that represents + * the exception types declared by this constructor, in declaration order. + * An array of size zero is returned if this constructor declares no + * exceptions. + * + * @return the exception types declared by this constructor. + * @throws GenericSignatureFormatError if the generic signature does + * not conform to the format specified in the Virtual Machine + * specification, version 3. + * @since 1.5 + */ + public Type[] getGenericExceptionTypes() + { + if (p == null) + { + String sig = cons.getSignature(); + if (sig == null) + return getExceptionTypes(); + p = new MethodSignatureParser(this, sig); + } + return p.getGenericExceptionTypes(); + } + + /** + * Returns an array of <code>Type</code> objects that represents + * the parameter list for this constructor, in declaration order. + * An array of size zero is returned if this constructor takes no + * parameters. + * + * @return a list of the types of the constructor's parameters + * @throws GenericSignatureFormatError if the generic signature does + * not conform to the format specified in the Virtual Machine + * specification, version 3. + * @since 1.5 + */ + public Type[] getGenericParameterTypes() + { + if (p == null) + { + String sig = cons.getSignature(); + if (sig == null) + return getParameterTypes(); + p = new MethodSignatureParser(this, sig); + } + return p.getGenericParameterTypes(); + } + + /** + * <p> + * Return an array of arrays representing the annotations on each + * of the constructor's parameters. The outer array is aligned against + * the parameters of the constructors and is thus equal in length to + * the number of parameters (thus having a length zero if there are none). + * Each array element in the outer array contains an inner array which + * holds the annotations. This array has a length of zero if the parameter + * has no annotations. + * </p> + * <p> + * The returned annotations are serialized. Changing the annotations has + * no affect on the return value of future calls to this method. + * </p> + * + * @return an array of arrays which represents the annotations used on the + * parameters of this constructor. The order of the array elements + * matches the declaration order of the parameters. + * @since 1.5 + */ + public Annotation[][] getParameterAnnotations() + { + return cons.getParameterAnnotations(); + } + + /** + * Returns the element's annotation for the specified annotation type, + * or <code>null</code> if no such annotation exists. + * + * @param annotationClass the type of annotation to look for. + * @return this element's annotation for the specified type, or + * <code>null</code> if no such annotation exists. + * @throws NullPointerException if the annotation class is <code>null</code>. + */ + public <T extends Annotation> T getAnnotation(Class<T> annotationClass) + { + // Inescapable as the VM layer is 1.4 based. + @SuppressWarnings("unchecked") + T ann = (T) cons.getAnnotation(annotationClass); + return ann; + } + + /** + * Returns all annotations directly defined by the element. If there are + * no annotations directly associated with the element, then a zero-length + * array will be returned. The returned array may be modified by the client + * code, but this will have no effect on the annotation content of this + * class, and hence no effect on the return value of this method for + * future callers. + * + * @return the annotations directly defined by the element. + * @since 1.5 + */ + public Annotation[] getDeclaredAnnotations() + { + return cons.getDeclaredAnnotations(); + } + +} diff --git a/libjava/classpath/java/lang/reflect/Field.java b/libjava/classpath/java/lang/reflect/Field.java new file mode 100644 index 00000000000..b9d92884564 --- /dev/null +++ b/libjava/classpath/java/lang/reflect/Field.java @@ -0,0 +1,735 @@ +/* java.lang.reflect.Field - reflection of Java fields + Copyright (C) 1998, 2001, 2005, 2008 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package java.lang.reflect; + +import gnu.java.lang.ClassHelper; +import gnu.java.lang.CPStringBuilder; + +import gnu.java.lang.reflect.FieldSignatureParser; + +import java.lang.annotation.Annotation; + +/** + * The Field class represents a member variable of a class. It also allows + * dynamic access to a member, via reflection. This works for both + * static and instance fields. Operations on Field objects know how to + * do widening conversions, but throw {@link IllegalArgumentException} if + * a narrowing conversion would be necessary. You can query for information + * on this Field regardless of location, but get and set access may be limited + * by Java language access controls. If you can't do it in the compiler, you + * can't normally do it here either.<p> + * + * <B>Note:</B> This class returns and accepts types as Classes, even + * primitive types; there are Class types defined that represent each + * different primitive type. They are <code>java.lang.Boolean.TYPE, + * java.lang.Byte.TYPE,</code>, also available as <code>boolean.class, + * byte.class</code>, etc. These are not to be confused with the + * classes <code>java.lang.Boolean, java.lang.Byte</code>, etc., which are + * real classes.<p> + * + * Also note that this is not a serializable class. It is entirely feasible + * to make it serializable using the Externalizable interface, but this is + * on Sun, not me. + * + * @author John Keiser + * @author Eric Blake <ebb9@email.byu.edu> + * @see Member + * @see Class + * @see Class#getField(String) + * @see Class#getDeclaredField(String) + * @see Class#getFields() + * @see Class#getDeclaredFields() + * @since 1.1 + * @status updated to 1.4 + */ +public final class Field +extends AccessibleObject implements Member +{ + static final int FIELD_MODIFIERS + = Modifier.FINAL | Modifier.PRIVATE | Modifier.PROTECTED + | Modifier.PUBLIC | Modifier.STATIC | Modifier.TRANSIENT + | Modifier.VOLATILE; + + private FieldSignatureParser p; + + VMField f; + + /** + * This class is uninstantiable outside the package. + */ + Field(VMField f) + { + this.f = f; + f.f = this; + } + + /** + * Gets the class that declared this field, or the class where this field + * is a non-inherited member. + * @return the class that declared this member + */ + public Class<?> getDeclaringClass() + { + return (Class<?>) f.getDeclaringClass(); + } + + /** + * Gets the name of this field. + * @return the name of this field + */ + public String getName() + { + return f.getName(); + } + + /** + * Gets the modifiers this field uses. Use the <code>Modifier</code> + * class to interpret the values. A field can only have a subset of the + * following modifiers: public, private, protected, static, final, + * transient, and volatile. + * + * @return an integer representing the modifiers to this Member + * @see Modifier + */ + public int getModifiers() + { + return f.getModifiersInternal() & FIELD_MODIFIERS; + } + + /** + * Return true if this field is synthetic, false otherwise. + * @since 1.5 + */ + public boolean isSynthetic() + { + return (f.getModifiersInternal() & Modifier.SYNTHETIC) != 0; + } + + /** + * Return true if this field represents an enum constant, + * false otherwise. + * @since 1.5 + */ + public boolean isEnumConstant() + { + return (f.getModifiersInternal() & Modifier.ENUM) != 0; + } + + /** + * Gets the type of this field. + * @return the type of this field + */ + public Class<?> getType() + { + return f.getType(); + } + + /** + * Compare two objects to see if they are semantically equivalent. + * Two Fields are semantically equivalent if they have the same declaring + * class, name, and type. Since you can't creat a Field except through + * the VM, this is just the == relation. + * + * @param o the object to compare to + * @return <code>true</code> if they are equal; <code>false</code> if not + */ + public boolean equals(Object o) + { + return f.equals(o); + } + + /** + * Get the hash code for the Field. The Field hash code is the hash code + * of its name XOR'd with the hash code of its class name. + * + * @return the hash code for the object. + */ + public int hashCode() + { + return f.getDeclaringClass().getName().hashCode() ^ f.getName().hashCode(); + } + + /** + * Get a String representation of the Field. A Field's String + * representation is "<modifiers> <type> + * <class>.<fieldname>".<br> Example: + * <code>public transient boolean gnu.parse.Parser.parseComplete</code> + * + * @return the String representation of the Field + */ + public String toString() + { + // 64 is a reasonable buffer initial size for field + CPStringBuilder sb = new CPStringBuilder(64); + Modifier.toString(getModifiers(), sb).append(' '); + sb.append(ClassHelper.getUserName(getType())).append(' '); + sb.append(getDeclaringClass().getName()).append('.'); + sb.append(getName()); + return sb.toString(); + } + + public String toGenericString() + { + CPStringBuilder sb = new CPStringBuilder(64); + Modifier.toString(getModifiers(), sb).append(' '); + sb.append(getGenericType()).append(' '); + sb.append(getDeclaringClass().getName()).append('.'); + sb.append(getName()); + return sb.toString(); + } + + /** + * Get the value of this Field. If it is primitive, it will be wrapped + * in the appropriate wrapper type (boolean = java.lang.Boolean).<p> + * + * If the field is static, <code>o</code> will be ignored. Otherwise, if + * <code>o</code> is null, you get a <code>NullPointerException</code>, + * and if it is incompatible with the declaring class of the field, you + * get an <code>IllegalArgumentException</code>.<p> + * + * Next, if this Field enforces access control, your runtime context is + * evaluated, and you may have an <code>IllegalAccessException</code> if + * you could not access this field in similar compiled code. If the field + * is static, and its class is uninitialized, you trigger class + * initialization, which may end in a + * <code>ExceptionInInitializerError</code>.<p> + * + * Finally, the field is accessed, and primitives are wrapped (but not + * necessarily in new objects). This method accesses the field of the + * declaring class, even if the instance passed in belongs to a subclass + * which declares another field to hide this one. + * + * @param o the object to get the value of this Field from + * @return the value of the Field + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if <code>o</code> is not an instance of + * the class or interface declaring this field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #getBoolean(Object) + * @see #getByte(Object) + * @see #getChar(Object) + * @see #getShort(Object) + * @see #getInt(Object) + * @see #getLong(Object) + * @see #getFloat(Object) + * @see #getDouble(Object) + */ + public Object get(Object o) + throws IllegalAccessException + { + return f.get(o); + } + + /** + * Get the value of this boolean Field. If the field is static, + * <code>o</code> will be ignored. + * + * @param o the object to get the value of this Field from + * @return the value of the Field + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not a boolean field of + * <code>o</code>, or if <code>o</code> is not an instance of the + * declaring class of this field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #get(Object) + */ + public boolean getBoolean(Object o) + throws IllegalAccessException + { + return f.getBoolean(o); + } + + /** + * Get the value of this byte Field. If the field is static, + * <code>o</code> will be ignored. + * + * @param o the object to get the value of this Field from + * @return the value of the Field + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not a byte field of + * <code>o</code>, or if <code>o</code> is not an instance of the + * declaring class of this field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #get(Object) + */ + public byte getByte(Object o) + throws IllegalAccessException + { + return f.getByte(o); + } + + /** + * Get the value of this Field as a char. If the field is static, + * <code>o</code> will be ignored. + * + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not a char field of + * <code>o</code>, or if <code>o</code> is not an instance + * of the declaring class of this field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #get(Object) + */ + public char getChar(Object o) + throws IllegalAccessException + { + return f.getChar(o); + } + + /** + * Get the value of this Field as a short. If the field is static, + * <code>o</code> will be ignored. + * + * @param o the object to get the value of this Field from + * @return the value of the Field + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not a byte or short + * field of <code>o</code>, or if <code>o</code> is not an instance + * of the declaring class of this field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #get(Object) + */ + public short getShort(Object o) + throws IllegalAccessException + { + return f.getShort(o); + } + + /** + * Get the value of this Field as an int. If the field is static, + * <code>o</code> will be ignored. + * + * @param o the object to get the value of this Field from + * @return the value of the Field + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not a byte, short, char, or + * int field of <code>o</code>, or if <code>o</code> is not an + * instance of the declaring class of this field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #get(Object) + */ + public int getInt(Object o) + throws IllegalAccessException + { + return f.getInt(o); + } + + /** + * Get the value of this Field as a long. If the field is static, + * <code>o</code> will be ignored. + * + * @param o the object to get the value of this Field from + * @return the value of the Field + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not a byte, short, char, int, + * or long field of <code>o</code>, or if <code>o</code> is not an + * instance of the declaring class of this field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #get(Object) + */ + public long getLong(Object o) + throws IllegalAccessException + { + return f.getLong(o); + } + + /** + * Get the value of this Field as a float. If the field is static, + * <code>o</code> will be ignored. + * + * @param o the object to get the value of this Field from + * @return the value of the Field + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not a byte, short, char, int, + * long, or float field of <code>o</code>, or if <code>o</code> is + * not an instance of the declaring class of this field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #get(Object) + */ + public float getFloat(Object o) + throws IllegalAccessException + { + return f.getFloat(o); + } + + /** + * Get the value of this Field as a double. If the field is static, + * <code>o</code> will be ignored. + * + * @param o the object to get the value of this Field from + * @return the value of the Field + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not a byte, short, char, int, + * long, float, or double field of <code>o</code>, or if + * <code>o</code> is not an instance of the declaring class of this + * field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #get(Object) + */ + public double getDouble(Object o) + throws IllegalAccessException + { + return f.getDouble(o); + } + + /** + * Set the value of this Field. If it is a primitive field, the value + * will be unwrapped from the passed object (boolean = java.lang.Boolean).<p> + * + * If the field is static, <code>o</code> will be ignored. Otherwise, if + * <code>o</code> is null, you get a <code>NullPointerException</code>, + * and if it is incompatible with the declaring class of the field, you + * get an <code>IllegalArgumentException</code>.<p> + * + * Next, if this Field enforces access control, your runtime context is + * evaluated, and you may have an <code>IllegalAccessException</code> if + * you could not access this field in similar compiled code. This also + * occurs whether or not there is access control if the field is final. + * If the field is primitive, and unwrapping your argument fails, you will + * get an <code>IllegalArgumentException</code>; likewise, this error + * happens if <code>value</code> cannot be cast to the correct object type. + * If the field is static, and its class is uninitialized, you trigger class + * initialization, which may end in a + * <code>ExceptionInInitializerError</code>.<p> + * + * Finally, the field is set with the widened value. This method accesses + * the field of the declaring class, even if the instance passed in belongs + * to a subclass which declares another field to hide this one. + * + * @param o the object to set this Field on + * @param value the value to set this Field to + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if <code>value</code> cannot be + * converted by a widening conversion to the underlying type of + * the Field, or if <code>o</code> is not an instance of the class + * declaring this field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #setBoolean(Object, boolean) + * @see #setByte(Object, byte) + * @see #setChar(Object, char) + * @see #setShort(Object, short) + * @see #setInt(Object, int) + * @see #setLong(Object, long) + * @see #setFloat(Object, float) + * @see #setDouble(Object, double) + */ + public void set(Object o, Object value) + throws IllegalAccessException + { + f.set(o, value); + } + + /** + * Set this boolean Field. If the field is static, <code>o</code> will be + * ignored. + * + * @param o the object to set this Field on + * @param value the value to set this Field to + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not a boolean field, or if + * <code>o</code> is not an instance of the class declaring this + * field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #set(Object, Object) + */ + public void setBoolean(Object o, boolean value) + throws IllegalAccessException + { + f.setBoolean(o, value); + } + + /** + * Set this byte Field. If the field is static, <code>o</code> will be + * ignored. + * + * @param o the object to set this Field on + * @param value the value to set this Field to + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not a byte, short, int, long, + * float, or double field, or if <code>o</code> is not an instance + * of the class declaring this field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #set(Object, Object) + */ + public void setByte(Object o, byte value) + throws IllegalAccessException + { + f.setByte(o, value); + } + + /** + * Set this char Field. If the field is static, <code>o</code> will be + * ignored. + * + * @param o the object to set this Field on + * @param value the value to set this Field to + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not a char, int, long, + * float, or double field, or if <code>o</code> is not an instance + * of the class declaring this field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #set(Object, Object) + */ + public void setChar(Object o, char value) + throws IllegalAccessException + { + f.setChar(o, value); + } + + /** + * Set this short Field. If the field is static, <code>o</code> will be + * ignored. + * + * @param o the object to set this Field on + * @param value the value to set this Field to + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not a short, int, long, + * float, or double field, or if <code>o</code> is not an instance + * of the class declaring this field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #set(Object, Object) + */ + public void setShort(Object o, short value) + throws IllegalAccessException + { + f.setShort(o, value); + } + + /** + * Set this int Field. If the field is static, <code>o</code> will be + * ignored. + * + * @param o the object to set this Field on + * @param value the value to set this Field to + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not an int, long, float, or + * double field, or if <code>o</code> is not an instance of the + * class declaring this field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #set(Object, Object) + */ + public void setInt(Object o, int value) + throws IllegalAccessException + { + f.setInt(o, value); + } + + /** + * Set this long Field. If the field is static, <code>o</code> will be + * ignored. + * + * @param o the object to set this Field on + * @param value the value to set this Field to + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not a long, float, or double + * field, or if <code>o</code> is not an instance of the class + * declaring this field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #set(Object, Object) + */ + public void setLong(Object o, long value) + throws IllegalAccessException + { + f.setLong(o, value); + } + + /** + * Set this float Field. If the field is static, <code>o</code> will be + * ignored. + * + * @param o the object to set this Field on + * @param value the value to set this Field to + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not a float or long field, or + * if <code>o</code> is not an instance of the class declaring this + * field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #set(Object, Object) + */ + public void setFloat(Object o, float value) + throws IllegalAccessException + { + f.setFloat(o, value); + } + + /** + * Set this double Field. If the field is static, <code>o</code> will be + * ignored. + * + * @param o the object to set this Field on + * @param value the value to set this Field to + * @throws IllegalAccessException if you could not normally access this field + * (i.e. it is not public) + * @throws IllegalArgumentException if this is not a double field, or if + * <code>o</code> is not an instance of the class declaring this + * field + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static field triggered + * class initialization, which then failed + * @see #set(Object, Object) + */ + public void setDouble(Object o, double value) + throws IllegalAccessException + { + f.setDouble(o, value); + } + + /** + * Return the generic type of the field. If the field type is not a generic + * type, the method returns the same as <code>getType()</code>. + * + * @throws GenericSignatureFormatError if the generic signature does + * not conform to the format specified in the Virtual Machine + * specification, version 3. + * @since 1.5 + */ + public Type getGenericType() + { + if (p == null) + { + String signature = f.getSignature(); + if (signature == null) + return getType(); + p = new FieldSignatureParser(getDeclaringClass(), + signature); + } + return p.getFieldType(); + } + + /** + * Returns the element's annotation for the specified annotation type, + * or <code>null</code> if no such annotation exists. + * + * @param annotationClass the type of annotation to look for. + * @return this element's annotation for the specified type, or + * <code>null</code> if no such annotation exists. + * @throws NullPointerException if the annotation class is <code>null</code>. + */ + public <T extends Annotation> T getAnnotation(Class<T> annotationClass) + { + // Inescapable as the VM layer is 1.4 based. T will erase to Annotation anyway. + @SuppressWarnings("unchecked") T ann = (T) f.getAnnotation(annotationClass); + return ann; + } + + /** + * Returns all annotations directly defined by the element. If there are + * no annotations directly associated with the element, then a zero-length + * array will be returned. The returned array may be modified by the client + * code, but this will have no effect on the annotation content of this + * class, and hence no effect on the return value of this method for + * future callers. + * + * @return the annotations directly defined by the element. + * @since 1.5 + */ + public Annotation[] getDeclaredAnnotations() + { + return f.getDeclaredAnnotations(); + } + +} diff --git a/libjava/classpath/java/lang/reflect/Method.java b/libjava/classpath/java/lang/reflect/Method.java new file mode 100644 index 00000000000..0a532ddb6f2 --- /dev/null +++ b/libjava/classpath/java/lang/reflect/Method.java @@ -0,0 +1,497 @@ +/* java.lang.reflect.Method - reflection of Java methods + Copyright (C) 1998, 2001, 2002, 2005, 2007, 2008 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package java.lang.reflect; + +import gnu.java.lang.ClassHelper; +import gnu.java.lang.CPStringBuilder; + +import gnu.java.lang.reflect.MethodSignatureParser; + +import java.lang.annotation.Annotation; + +/** + * The Method class represents a member method of a class. It also allows + * dynamic invocation, via reflection. This works for both static and + * instance methods. Invocation on Method objects knows how to do + * widening conversions, but throws {@link IllegalArgumentException} if + * a narrowing conversion would be necessary. You can query for information + * on this Method regardless of location, but invocation access may be limited + * by Java language access controls. If you can't do it in the compiler, you + * can't normally do it here either.<p> + * + * <B>Note:</B> This class returns and accepts types as Classes, even + * primitive types; there are Class types defined that represent each + * different primitive type. They are <code>java.lang.Boolean.TYPE, + * java.lang.Byte.TYPE,</code>, also available as <code>boolean.class, + * byte.class</code>, etc. These are not to be confused with the + * classes <code>java.lang.Boolean, java.lang.Byte</code>, etc., which are + * real classes.<p> + * + * Also note that this is not a serializable class. It is entirely feasible + * to make it serializable using the Externalizable interface, but this is + * on Sun, not me. + * + * @author John Keiser + * @author Eric Blake <ebb9@email.byu.edu> + * @see Member + * @see Class + * @see java.lang.Class#getMethod(String,Class[]) + * @see java.lang.Class#getDeclaredMethod(String,Class[]) + * @see java.lang.Class#getMethods() + * @see java.lang.Class#getDeclaredMethods() + * @since 1.1 + * @status updated to 1.4 + */ +public final class Method +extends AccessibleObject implements Member, GenericDeclaration +{ + private static final int METHOD_MODIFIERS + = Modifier.ABSTRACT | Modifier.FINAL | Modifier.NATIVE + | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC + | Modifier.STATIC | Modifier.STRICT | Modifier.SYNCHRONIZED; + + private MethodSignatureParser p; + + VMMethod m; + + /** + * This class is uninstantiable outside this package. + */ + Method(VMMethod m) + { + this.m = m; + m.m = this; + } + + /** + * Gets the class that declared this method, or the class where this method + * is a non-inherited member. + * @return the class that declared this member + */ + public Class<?> getDeclaringClass() + { + return (Class<?>) m.getDeclaringClass(); + } + + /** + * Gets the name of this method. + * @return the name of this method + */ + public String getName() + { + return m.getName(); + } + + /** + * Gets the modifiers this method uses. Use the <code>Modifier</code> + * class to interpret the values. A method can only have a subset of the + * following modifiers: public, private, protected, abstract, static, + * final, synchronized, native, and strictfp. + * + * @return an integer representing the modifiers to this Member + * @see Modifier + */ + public int getModifiers() + { + return m.getModifiersInternal() & METHOD_MODIFIERS; + } + + /** + * Return true if this method is a bridge method. A bridge method + * is generated by the compiler in some situations involving + * generics and inheritance. + * @since 1.5 + */ + public boolean isBridge() + { + return (m.getModifiersInternal() & Modifier.BRIDGE) != 0; + } + + /** + * Return true if this method is synthetic, false otherwise. + * @since 1.5 + */ + public boolean isSynthetic() + { + return (m.getModifiersInternal() & Modifier.SYNTHETIC) != 0; + } + + /** + * Return true if this is a varargs method, that is if + * the method takes a variable number of arguments. + * @since 1.5 + */ + public boolean isVarArgs() + { + return (m.getModifiersInternal() & Modifier.VARARGS) != 0; + } + + /** + * Gets the return type of this method. + * @return the type of this method + */ + public Class<?> getReturnType() + { + return (Class<?>) m.getReturnType(); + } + + /** + * Get the parameter list for this method, in declaration order. If the + * method takes no parameters, returns a 0-length array (not null). + * + * @return a list of the types of the method's parameters + */ + public Class<?>[] getParameterTypes() + { + return (Class<?>[]) m.getParameterTypes(); + } + + /** + * Get the exception types this method says it throws, in no particular + * order. If the method has no throws clause, returns a 0-length array + * (not null). + * + * @return a list of the types in the method's throws clause + */ + public Class<?>[] getExceptionTypes() + { + return (Class<?>[]) m.getExceptionTypes(); + } + + /** + * Compare two objects to see if they are semantically equivalent. + * Two Methods are semantically equivalent if they have the same declaring + * class, name, parameter list, and return type. + * + * @param o the object to compare to + * @return <code>true</code> if they are equal; <code>false</code> if not + */ + public boolean equals(Object o) + { + return m.equals(o); + } + + /** + * Get the hash code for the Method. The Method hash code is the hash code + * of its name XOR'd with the hash code of its class name. + * + * @return the hash code for the object + */ + public int hashCode() + { + return m.getDeclaringClass().getName().hashCode() ^ m.getName().hashCode(); + } + + /** + * Get a String representation of the Method. A Method's String + * representation is "<modifiers> <returntype> + * <methodname>(<paramtypes>) throws <exceptions>", where + * everything after ')' is omitted if there are no exceptions.<br> Example: + * <code>public static int run(java.lang.Runnable,int)</code> + * + * @return the String representation of the Method + */ + public String toString() + { + // 128 is a reasonable buffer initial size for constructor + CPStringBuilder sb = new CPStringBuilder(128); + Modifier.toString(getModifiers(), sb).append(' '); + sb.append(ClassHelper.getUserName(getReturnType())).append(' '); + sb.append(getDeclaringClass().getName()).append('.'); + sb.append(getName()).append('('); + Class[] c = getParameterTypes(); + if (c.length > 0) + { + sb.append(ClassHelper.getUserName(c[0])); + for (int i = 1; i < c.length; i++) + sb.append(',').append(ClassHelper.getUserName(c[i])); + } + sb.append(')'); + c = getExceptionTypes(); + if (c.length > 0) + { + sb.append(" throws ").append(c[0].getName()); + for (int i = 1; i < c.length; i++) + sb.append(',').append(c[i].getName()); + } + return sb.toString(); + } + + public String toGenericString() + { + // 128 is a reasonable buffer initial size for constructor + CPStringBuilder sb = new CPStringBuilder(128); + Modifier.toString(getModifiers(), sb).append(' '); + Constructor.addTypeParameters(sb, getTypeParameters()); + sb.append(getGenericReturnType()).append(' '); + sb.append(getDeclaringClass().getName()).append('.'); + sb.append(getName()).append('('); + Type[] types = getGenericParameterTypes(); + if (types.length > 0) + { + sb.append(types[0]); + for (int i = 1; i < types.length; i++) + sb.append(',').append(types[i]); + } + sb.append(')'); + types = getGenericExceptionTypes(); + if (types.length > 0) + { + sb.append(" throws ").append(types[0]); + for (int i = 1; i < types.length; i++) + sb.append(',').append(types[i]); + } + return sb.toString(); + } + + /** + * Invoke the method. Arguments are automatically unwrapped and widened, + * and the result is automatically wrapped, if needed.<p> + * + * If the method is static, <code>o</code> will be ignored. Otherwise, + * the method uses dynamic lookup as described in JLS 15.12.4.4. You cannot + * mimic the behavior of nonvirtual lookup (as in super.foo()). This means + * you will get a <code>NullPointerException</code> if <code>o</code> is + * null, and an <code>IllegalArgumentException</code> if it is incompatible + * with the declaring class of the method. If the method takes 0 arguments, + * you may use null or a 0-length array for <code>args</code>.<p> + * + * Next, if this Method enforces access control, your runtime context is + * evaluated, and you may have an <code>IllegalAccessException</code> if + * you could not acces this method in similar compiled code. If the method + * is static, and its class is uninitialized, you trigger class + * initialization, which may end in a + * <code>ExceptionInInitializerError</code>.<p> + * + * Finally, the method is invoked. If it completes normally, the return value + * will be null for a void method, a wrapped object for a primitive return + * method, or the actual return of an Object method. If it completes + * abruptly, the exception is wrapped in an + * <code>InvocationTargetException</code>. + * + * @param o the object to invoke the method on + * @param args the arguments to the method + * @return the return value of the method, wrapped in the appropriate + * wrapper if it is primitive + * @throws IllegalAccessException if the method could not normally be called + * by the Java code (i.e. it is not public) + * @throws IllegalArgumentException if the number of arguments is incorrect; + * if the arguments types are wrong even with a widening conversion; + * or if <code>o</code> is not an instance of the class or interface + * declaring this method + * @throws InvocationTargetException if the method throws an exception + * @throws NullPointerException if <code>o</code> is null and this field + * requires an instance + * @throws ExceptionInInitializerError if accessing a static method triggered + * class initialization, which then failed + */ + public Object invoke(Object o, Object... args) + throws IllegalAccessException, InvocationTargetException + { + return m.invoke(o, args); + } + + /** + * Returns an array of <code>TypeVariable</code> objects that represents + * the type variables declared by this constructor, in declaration order. + * An array of size zero is returned if this class has no type + * variables. + * + * @return the type variables associated with this class. + * @throws GenericSignatureFormatError if the generic signature does + * not conform to the format specified in the Virtual Machine + * specification, version 3. + * @since 1.5 + */ + public TypeVariable<Method>[] getTypeParameters() + { + if (p == null) + { + String sig = m.getSignature(); + if (sig == null) + return (TypeVariable<Method>[]) new TypeVariable[0]; + p = new MethodSignatureParser(this, sig); + } + return p.getTypeParameters(); + } + + /** + * Returns an array of <code>Type</code> objects that represents + * the exception types declared by this method, in declaration order. + * An array of size zero is returned if this method declares no + * exceptions. + * + * @return the exception types declared by this method. + * @throws GenericSignatureFormatError if the generic signature does + * not conform to the format specified in the Virtual Machine + * specification, version 3. + * @since 1.5 + */ + public Type[] getGenericExceptionTypes() + { + if (p == null) + { + String sig = m.getSignature(); + if (sig == null) + return getExceptionTypes(); + p = new MethodSignatureParser(this, sig); + } + return p.getGenericExceptionTypes(); + } + + /** + * Returns an array of <code>Type</code> objects that represents + * the parameter list for this method, in declaration order. + * An array of size zero is returned if this method takes no + * parameters. + * + * @return a list of the types of the method's parameters + * @throws GenericSignatureFormatError if the generic signature does + * not conform to the format specified in the Virtual Machine + * specification, version 3. + * @since 1.5 + */ + public Type[] getGenericParameterTypes() + { + if (p == null) + { + String sig = m.getSignature(); + if (sig == null) + return getParameterTypes(); + p = new MethodSignatureParser(this, sig); + } + return p.getGenericParameterTypes(); + } + + /** + * Returns the return type of this method. + * + * @return the return type of this method + * @throws GenericSignatureFormatError if the generic signature does + * not conform to the format specified in the Virtual Machine + * specification, version 3. + * @since 1.5 + */ + public Type getGenericReturnType() + { + if (p == null) + { + String sig = m.getSignature(); + if (sig == null) + return getReturnType(); + p = new MethodSignatureParser(this, sig); + } + return p.getGenericReturnType(); + } + + /** + * If this method is an annotation method, returns the default + * value for the method. If there is no default value, or if the + * method is not a member of an annotation type, returns null. + * Primitive types are wrapped. + * + * @throws TypeNotPresentException if the method returns a Class, + * and the class cannot be found + * + * @since 1.5 + */ + public Object getDefaultValue() + { + return m.getDefaultValue(); + } + + /** + * <p> + * Return an array of arrays representing the annotations on each + * of the method's parameters. The outer array is aligned against + * the parameters of the method and is thus equal in length to + * the number of parameters (thus having a length zero if there are none). + * Each array element in the outer array contains an inner array which + * holds the annotations. This array has a length of zero if the parameter + * has no annotations. + * </p> + * <p> + * The returned annotations are serialized. Changing the annotations has + * no affect on the return value of future calls to this method. + * </p> + * + * @return an array of arrays which represents the annotations used on the + * parameters of this method. The order of the array elements + * matches the declaration order of the parameters. + * @since 1.5 + */ + public Annotation[][] getParameterAnnotations() + { + return m.getParameterAnnotations(); + } + + /** + * Returns the element's annotation for the specified annotation type, + * or <code>null</code> if no such annotation exists. + * + * @param annotationClass the type of annotation to look for. + * @return this element's annotation for the specified type, or + * <code>null</code> if no such annotation exists. + * @throws NullPointerException if the annotation class is <code>null</code>. + */ + public <T extends Annotation> T getAnnotation(Class<T> annotationClass) + { + // Inescapable as the VM layer is 1.4 based. T will erase to Annotation anyway. + @SuppressWarnings("unchecked") + T ann = (T) m.getAnnotation(annotationClass); + return ann; + } + + /** + * Returns all annotations directly defined by the element. If there are + * no annotations directly associated with the element, then a zero-length + * array will be returned. The returned array may be modified by the client + * code, but this will have no effect on the annotation content of this + * class, and hence no effect on the return value of this method for + * future callers. + * + * @return the annotations directly defined by the element. + * @since 1.5 + */ + public Annotation[] getDeclaredAnnotations() + { + return m.getDeclaredAnnotations(); + } + +} diff --git a/libjava/classpath/java/lang/reflect/Modifier.java b/libjava/classpath/java/lang/reflect/Modifier.java index 45fc4e37e69..45d9b51a75e 100644 --- a/libjava/classpath/java/lang/reflect/Modifier.java +++ b/libjava/classpath/java/lang/reflect/Modifier.java @@ -1,5 +1,5 @@ /* java.lang.reflect.Modifier - Copyright (C) 1998, 1999, 2001, 2002, 2005 Free Software Foundation, Inc. + Copyright (C) 1998, 1999, 2001, 2002, 2005, 2008 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -38,6 +38,8 @@ exception statement from your version. */ package java.lang.reflect; +import gnu.java.lang.CPStringBuilder; + /** * Modifier is a helper class with static methods to determine whether an * int returned from getModifiers() represents static, public, protected, @@ -308,28 +310,16 @@ public class Modifier */ public static String toString(int mod) { - return toString(mod, new StringBuilder()).toString(); - } - - /** - * Package helper method that can take a StringBuilder. - * @param mod the modifier - * @param r the StringBuilder to which the String representation is appended - * @return r, with information appended - */ - static StringBuilder toString(int mod, StringBuilder r) - { - r.append(toString(mod, new StringBuffer())); - return r; + return toString(mod, new CPStringBuilder()).toString(); } /** - * Package helper method that can take a StringBuffer. + * Package helper method that can take a CPStringBuilder. * @param mod the modifier - * @param r the StringBuffer to which the String representation is appended + * @param r the CPStringBuilder to which the String representation is appended * @return r, with information appended */ - static StringBuffer toString(int mod, StringBuffer r) + static CPStringBuilder toString(int mod, CPStringBuilder r) { if (isPublic(mod)) r.append("public "); diff --git a/libjava/classpath/java/lang/reflect/Proxy.java b/libjava/classpath/java/lang/reflect/Proxy.java index 6c1e975a287..fb2004e790b 100644 --- a/libjava/classpath/java/lang/reflect/Proxy.java +++ b/libjava/classpath/java/lang/reflect/Proxy.java @@ -38,6 +38,8 @@ exception statement from your version. */ package java.lang.reflect; +import gnu.java.lang.CPStringBuilder; + import gnu.java.lang.reflect.TypeSignature; import java.io.Serializable; @@ -1033,7 +1035,7 @@ public class Proxy implements Serializable code_length += 9; // new, dup_x1, swap, invokespecial, athrow } int handler_pc = code_length - 1; - StringBuilder signature = new StringBuilder("("); + CPStringBuilder signature = new CPStringBuilder("("); for (int j = 0; j < paramtypes.length; j++) signature.append(TypeSignature.getEncodingOfClass(paramtypes[j])); signature.append(")").append(TypeSignature.getEncodingOfClass(ret_type)); @@ -1492,7 +1494,7 @@ public class Proxy implements Serializable if (i == len) return str; - final StringBuilder sb = new StringBuilder(str); + final CPStringBuilder sb = new CPStringBuilder(str); sb.setLength(i); for ( ; i < len; i++) { |