Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 52 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
52
Dung lượng
0,98 MB
Nội dung
J2ME in a Nutshell 359 Runtime CLDC 1.0, MIDP 1.0 java.lang The Runtime class contains methods and variables that provide access to low-level facilities provided by the Java virtual machine. In order to access these facilities, application code must first use the static getRuntime() method to obtain an instance of the Runtime class. The CLDC version of this class contains only a small subset of the functionality of its J2SE counterpart. The exit() method causes the virtual machine to terminate. A CLDC application is permitted to use this method. However, a MIDlet will receive a SecurityException if it attempts to do so. The gc() method hints to the garbage collector that it should attempt to reclaim unreferenced memory. Garbage collectors implemented in small-footprint virtual machines (e,g, the KVM) are typically quite agressive at cleaning up unused memory, so the programmer should not have to call this method very often. The totalMemory() method returns the total amount of memory, in bytes, occupied by the Java virtual machine. In some environments, demand for more memory can cause this value to increase as the VM uses extra system resources. The freeMemory() method returns a value that indicates approximately how much of the total memory occupied by the Java VM is free for allocation to new objects. public class Runtime { // No Constructor // Public Class Methods public static Runtime getRuntime(); // Public Instance Methods public void exit( int status); public long freeMemory(); // native public void gc(); // native public long totalMemory(); // native } Returned By Runtime.getRuntime() RuntimeException CLDC 1.0, MIDP 1.0 java.lang unchecked A base class for Exception subclasses that need not be be declared in the throws clause of a method definition and, consequently, application code need not catch. Exceptions of this type are generally caused by programming errors and need to be addressed during application development, rather than attempting recovery at run time. This class is the same as its J2SE equivalent, apart from its inability to be serialized. J2ME in a Nutshell 360 public class RuntimeException extends Exception { // Public Constructors public RuntimeException(); public RuntimeException( String s); } Subclasses ArithmeticException, ArrayStoreException, ClassCastException, IllegalArgumentException, IllegalMonitorStateException, IllegalStateException, IndexOutOfBoundsException, NegativeArraySizeException, NullPointerException, SecurityException, java.util.EmptyStackException, java.util.NoSuchElementException SecurityException CLDC 1.0, MIDP 1.0 java.lang unchecked This exception signals that a run time security check has been violated. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class SecurityException extends RuntimeException { // Public Constructors public SecurityException(); public SecurityException( String s); } Short CLDC 1.0, MIDP 1.0 java.lang Short provides an object wrapper for a Java short primitive. The constructor initializes the wrapper with a short value, after which the object becomes immutable. The value associated with a Short object can be retrieved using the shortValue() method. The static parseShort() converts a numeric value held in a String into a primitive short. The single-argument variant of this method assumes that the String is encoded in base 10; the two-argument variant can be used to specify a different number base if necessary. A NumberFormatException is thrown if the String does not represent a valid number in the given number base. The static variables Short.MIN_VALUE and Short.MAX_VALUE are short (not Short) values that represent the smallest and largest values, respectively, that can be held in a short primitive. J2ME in a Nutshell 361 Note that this class is derived from Object and not Number. This is because CLDC does not provide the Number class. public final class Short { // Public Constructors public Short( short value); // Public Constants public static final short MAX_VALUE; // =32767 public static final short MIN_VALUE; // =-32768 // Public Class Methods public static short parseShort( String s) throws NumberFormatException; public static short parseShort(String s, int radix) throws NumberFormatException; // Public Instance Methods public short shortValue(); // Public Methods Overriding Object public boolean equals( Object obj); public int hashCode(); public String toString(); } String CLDC 1.0, MIDP 1.0 java.lang This class represents a immutable character string. Operations on String objects that change their content actually place their results in other String objects. When concatenating strings or changing the values of characters within a string, it is more efficient to use a StringBuffer instead. The CLDC String class is similar to its J2SE equivalent, but lacks the following methods: compareToIgnoreCase(), copyValueOf(), equalsIgnoreCase() and intern(). It also does not contain the variants of lastIndexOf() that accept a String- valued argument, or the valueOf() methods for types float and double. A String can be constructed as a copy of another String, from the content of a StringBuffer, or from an array of characters or bytes. When constructing a String from bytes, the appropriate character encoding must be used; if an encoding is not specified, the platform's default encoding is assumed. A String can also be created by applying the static valueOf() methods to a boolean, a char, an array of characters (char[]), an int, a long or an arbitrary Java Object. With an Object, the String is created using the return value of the object's toString() method. The toCharArray() method returns an array of chars initialized with the content of the String. The getChars() method is similar, but requires the caller to allocate the destination array and can be used to extract a subset of the string. The getBytes() methods copy a subset of the String into a pre-allocated byte array, using either a specified encoding or the platform's default encoding. The charAt() method can be used to retrieve the value of a single character whose location is specified by a zero-based index. The length of the String, in characters, can be obtained using the length() method. J2ME in a Nutshell 362 There are several methods that can be used to compare strings or search the content of a string. The compareTo() method performs a comparison of one string with another; it returns 0 if they are equal, or a negative or positive value depending on whether the source string is lexicographically less than or greater than the string passed as an argument. The startsWith() and endsWith() method determine whether a string starts or ends with a sequence of characters represented by a second string, while the regionMatches() method determines whether a region of the string matches a given region (of the same length) of another string. The indexOf() method looks for either an individual character or a substring. It returns the offset at which the match was found, or -1 if there was no match, and the search may start either at the beginning of the String or from any specified index within it. The lastIndexOf() method is similar but returns the index of the last match for a given character, searching back either from the end of the string or from a given offset. Note that unlike indexOf(), there is no variant of lastIndexOf() that accepts a string-valued argument. The replace() method returns a new String object in which all occurrences of one character have been replaced by a second character. The substring() methods return a new String created from a given range of characters from the String to which it is applied. The toUpperCase() and toLowerCase() methods create a new String in which the characters of the original have been converted to upper- or lower-case respectively (characters that are not case-dependent are left unchanged.) The trim() method returns a new String formed by removing all leading and trailing white space from the String to which it is applied. public final class String { // Public Constructors public String(); public String( byte[] bytes); public String( String value); public String( char[] value); public String( StringBuffer buffer); public String(byte[] bytes, String enc) throws java.io.UnsupportedEncodingException; public String( byte[] bytes, int off, int len); public String(char[] value, int offset, int count); public String(byte[] bytes, int off, int len, String enc) throws java.io.UnsupportedEncodingException; // Public Class Methods public static String valueOf( char c); public static String valueOf( int i); public static String valueOf( long l); public static String valueOf( boolean b); public static String valueOf( Object obj); public static String valueOf( char[] data); public static String valueOf(char[] data, int offset, int count); // Public Instance Methods public char charAt( int index); // native public int compareTo( String anotherString); public String concat( String str); public boolean endsWith( String suffix); public byte[] getBytes(); J2ME in a Nutshell 363 public byte[] getBytes( String enc) throws java.io.UnsupportedEncodingException; public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin); public int indexOf( int ch); // native public int indexOf( String str); public int indexOf( int ch, int fromIndex); // native public int indexOf( String str, int fromIndex); public int lastIndexOf( int ch); public int lastIndexOf( int ch, int fromIndex); public int length(); public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len); public String replace( char oldChar, char newChar); public boolean startsWith( String prefix); public boolean startsWith( String prefix, int toffset); public String substring( int beginIndex); public String substring( int beginIndex, int endIndex); public char[] toCharArray(); public String toLowerCase(); public String toUpperCase(); public String trim(); // Public Methods Overriding Object public boolean equals( Object anObject); // native public int hashCode(); public String toString(); } Passed To Too many methods to list. Returned By Too many methods to list. Type Of javax.microedition.io.HttpConnection.{GET, HEAD, POST} StringBuffer CLDC 1.0, MIDP 1.0 java.lang A StringBuffer is an array of characters that can be expanded or contracted as necessary. StringBuffers are typically used to construct an array of characters that is then converted into an immutable String. The characters that make up the content of a StringBuffer are held in an internal array. The number of entries in the array is referred to as the capacity of the StringBuffer, while the actual number of characters in use is referred to as its size. A StringBuffer is constructed with a specific initial capacity (the default is 16 characters). It can also be constructed from J2ME in a Nutshell 364 the content of a String, in which case an appropriate initial capacity is determined. When the size approaches the capacity, a new character array is allocated and the existing characters are copied into it. Note that this can be a costly operation that may have to be repeated if the StringBuffer's size grows continuously. If possible, the StringBuffer should be created with sufficient capacity to hold all of the characters that it will contain. Following construction, the ensureCapacity() method is used to ensure that the internal array can hold at least the number of characters specified without needing to be expanded any further. capacity() returns the current capacity of the StringBuffer, while length() returns its actual size. The actual number of characters in use can be changed by calling the setLength() method. If the new length is smaller than the old length, the characters at the end are lost. If it is larger, null characters are appended. A common use of a StringBuffer is to concatenate several Strings. This can be achieved by using one of the overloaded append() methods, which accept arguments of type boolean, char, char[], int, long, Object and String. These methods convert the target data value to character form and add its content to the end of the internal array. Each of these methods returns a reference to the StringBuffer itself, so that the programmer can chain commands together (e.g., sb.append("x = ").append(x)). The toString() method is used to convert the characters in a StringBuffer into an immutable String. It is also possible to insert content into a StringBuffer using one of the insert() methods, which has the same variants as the append() methods. These methods insert characters before the position given by the specified index, shifting all characters that follow to higher indices. As with append(), these methods also return a reference to the StringBuffer to allow command chaining. The value of a single character can be changed using the setCharAt() method; this method supplies the new character value and the index of the character to replace. Characters can be removed from the StringBuffer using the delete() and deleteCharAt() methods. Finally, the content of the internal array can be reversed efficiently by calling reverse(). Apart from toString(), there are two ways to extract characters from a StringBuffer. To get the value of a single character, invoke the charAt() method with the index of the required character in the internal array. To get a range of characters in the form of a String, use one of the two variants of substring(). public final class StringBuffer { // Public Constructors public StringBuffer(); public StringBuffer( String str); public StringBuffer( int length); // Public Instance Methods public StringBuffer append( char[] str); // synchronized public StringBuffer append( String str); // native synchronized public StringBuffer append( Object obj); // synchronized public StringBuffer append( boolean b); public StringBuffer append( long l); public StringBuffer append( int i); // native public StringBuffer append( char c); // synchronized public StringBuffer append(char[] str, int offset, // synchronized int len); public int capacity(); J2ME in a Nutshell 365 public char charAt( int index); // synchronized public StringBuffer delete( int start, int end); // synchronized public StringBuffer deleteCharAt( int index); // synchronized public void ensureCapacity( int minimumCapacity); // synchronized public void getChars(int srcBegin, int srcEnd, // synchronized char[] dst, int dstBegin); public StringBuffer insert( int offset, int i); public StringBuffer insert( int offset, Object obj); // synchronized public StringBuffer insert( int offset, long l); public StringBuffer insert( int offset, boolean b); public StringBuffer insert( int offset, char c); // synchronized public StringBuffer insert(int offset, // synchronized char[] str); public StringBuffer insert( int offset, String str); // synchronized public int length(); public StringBuffer reverse(); // synchronized public void setCharAt( int index, char ch); // synchronized public void setLength( int newLength); // synchronized // Public Methods Overriding Object public String toString(); // native } Passed To String.String() Returned By Too many methods to list. StringIndexOutOfBoundsException CLDC 1.0, MIDP 1.0 java.lang unchecked This exception is thrown when an operation is attempted on a String or StringBuffer object involving an index that is either negative or too large. This class is the same as its J2SE equivalent, apart from its inability to be serialized. public class StringIndexOutOfBoundsException extends IndexOutOfBoundsException { // Public Constructors public StringIndexOutOfBoundsException(); public StringIndexOutOfBoundsException( int index); public StringIndexOutOfBoundsException( String s); } J2ME in a Nutshell 366 System CLDC 1.0, MIDP 1.0 java.lang The System class contains static methods and variables that provide access to low-level facilities. The CLDC version of this class contains only a small subset of the functionality of its J2SE counterpart. The public static variables out and err are PrintStream objects that can be used for standard output and error output. With J2ME, these streams are useful when running code in an emulated environment, where they typically result in the creation of log files. Note that there is no in variable as there is no standard input stream for a CLDC device. The currentTimeMillis() method returns the current time as a millisecond offset from 0:00 UTC on January 1st, 1970. This is the same representation used by the java.util.Date and java.util.Calendar classes. The exit() method causes the virtual machine to terminate. A CLDC application is permitted to invoke this method. However, a MIDlet will receive a SecurityException if it attempts to do so. The gc() method hints to the garbage collector that it should attempt to reclaim unreferenced memory. Note that the garbage collectors implemented in the small-footprint virtual machines (such as the KVM) are aggressive at cleaning up unused memory, so this method should not need to called very often. The identityHashCode() method returns a system-defined hash code for the object passed as its argument. This method returns the same value as the hashCode() method in the Object class would for the same object. It is provided as a convienence because many classes override the hashCode() method to return a different hash code. The arraycopy() method provides an efficient means of copying a portion of an array of objects into a separate array. The source and destination arrays may be the same. In addition, the source and target ranges may overlap. The getProperty() method returns the value of a named system property. CLDC does not provide any means to retrieve the complete list of available properties. Instead, an application must know beforehand the names of the properties that it accesses. The properties defined by CLDC are listed in Chapter 2; those for MIDP are listed in Chapter 3. public final class System { // No Constructor // Public Constants public static final java.io.PrintStream err; public static final java.io.PrintStream out; // Public Class Methods public static void arraycopy(Object src, int src_position, // native Object dst, int dst_position, int length); public static long currentTimeMillis(); // native public static void exit( int status); public static void gc(); J2ME in a Nutshell 367 public static String getProperty( String key); public static int identityHashCode( Object x); // native } Thread CLDC 1.0, MIDP 1.0 java.lang runnable A class that represents a thread of execution in the Java virtual machine. Each thread has its own call stack and its own copy of local variables created by the Java methods that it executes. An application may create a new thread of execution by instantiating a subclass of Thread and overriding the run() method, or by implementing a Runnable interface and passing its reference to the Thread constructor. A new thread is created in an inactive state. To begin execution, its start() method must be invoked. The total number of threads in existence can be obtained by calling the static activeCount() method. Once a thread is running, it continues to do so until the run() of the Thread subclass terminates, or the Runnable returns control to its caller. Note that even though its thread of execution has ended, a Thread object continues to exist until all references to it have been released and the object is removed by the garbage collector. The isAlive() method can be used to determine whether a Thread object still has an active thread of execution. Unlike J2SE, the CLDC Thread class does not provide the stop(), suspend() and resume() methods. However, there are two Thread methods that allow a thread to suspend its own execution. The static sleep() method suspends the thread for a fixed period of time specified in milliseconds. The thread will be scheduled for resumption when the delay period expires, but may not resume immediately if another thread is currently running. The join() method forces the current thread to block until the passed-in Thread thread terminates. Both sleep() and join() can throw an InterruptedException in the event of an interruption. (In practice, this is not likely to happen because the CLDC Thread does not include the J2SE interrupt() method.) The yield() method allows a thread to temporarily yield control to other threads that are waiting to run. Each thread has an execution priority that may be used when determining which thread should be chosen for execution. The setPriority() can be used to set a thread's priority and the getPriority() method used to retrieve it. Three standard priority levels (MIN_PRIORITY, NORM_PRIORITY and MAX_PRIORITY) are defined. Only priorities in the range of MIN_PRIORITY to MAX_PRIORITY inclusive are valid. Threads with higher priority that are ready to run are chosen in preference over those with lower priority. The algorithm used to choose between threads that have the same priority is not defined and therefore may be platform- and VM-dependent. The static currentThread() is used to obtain a reference to the Thread that is currently executing. This method can be used to allow a thread to perform operations on itself. J2ME in a Nutshell 368 public class Thread implements Runnable { // Public Constructors public Thread(); public Thread( Runnable target); // Public Constants public static final int MAX_PRIORITY; // =10 public static final int MIN_PRIORITY; // =1 public static final int NORM_PRIORITY; // =5 // Public Class Methods public static int activeCount(); // native public static Thread currentThread(); // native public static void sleep( // native long millis) throws InterruptedException; public static void yield(); // native // Public Instance Methods public final int getPriority(); // default:5 public final boolean isAlive(); // native default:false public final void join() throws InterruptedException; public final void setPriority( int newPriority); public void start(); // native synchronized // Methods Implementing Runnable public void run(); // Public Methods Overriding Object public String toString(); } Returned By Thread.currentThread() Throwable CLDC 1.0, MIDP 1.0 java.lang Throwable is the base class from which all Java exception types are derived. Throwable objects may be constructed with an associated message that provides diagnostic information relating to the cause of the exception. The message, if it is set, can be retrieved using the getMessage() method. Throwable has two subclasses that are base classes for different types of exceptions. The Error class and its subclasses describe errors that application code is not expected to recover from. J2SE has a large number of error subclasses; however, the CLDC supports only two of them. The Exception class is the base class for exceptions that an application can recover from. Application code is required to declare any Exceptions that it throws. It must also catch those exceptions thrown by methods that it invokes, apart from RuntimeException and its subclasses. A Throwable contains a stack backtrace that contains the method call stack at the point at which the exception was thrown. The stack trace may be printed using the printStackTrace() method. Unlike J2SE, the CLDC Throwable class does not include a stack trace when it is created and does not provide a fillInStackTrace() method to force [...]... public static final int FRIDAY; public static final int HOUR; public static final int HOUR_OF_DAY; public static final int JANUARY; public static final int JULY; public static final int JUNE; public static final int MARCH; public static final int MAY; public static final int MILLISECOND; public static final int MINUTE; public static final int MONDAY; public static final int MONTH; public static final int... static final int OCTOBER; public static final int PM; public static final int SATURDAY; public static final int SECOND; public static final int SEPTEMBER; public static final int SUNDAY; public static final int THURSDAY; public static final int TUESDAY; public static final int WEDNESDAY; public static final int YEAR; // Public Class Methods public static Calendar getInstance(); public static Calendar... Calendar public abstract class Calendar { // Protected Constructors protected Calendar(); // Public Constants public static final int AM; public static final int AM_PM; public static final int APRIL; public static final int AUGUST; public static final int DATE; public static final int DAY_OF_MONTH; public static final int DAY_OF_WEEK; public static final int DECEMBER; public static final int FEBRUARY;... abstract int getNominalLength( ) throws java.io.IOException; public abstract Datagram newDatagram( int size) throws java.io.IOException; public abstract Datagram newDatagram(byte[] buf, int size) throws java.io.IOException; public abstract Datagram newDatagram(int size, String addr) throws java.io.IOException; public abstract Datagram newDatagram(byte[] buf, int size, String addr) throws java.io.IOException;... final int HTTP_BAD_GATEWAY; public static final int HTTP_BAD_METHOD; public static final int HTTP_BAD_REQUEST; public static final int HTTP_CLIENT_TIMEOUT; public static final int HTTP_CONFLICT; public static final int HTTP_CREATED; public static final int HTTP_ENTITY_TOO_LARGE; public static final int HTTP_EXPECT_FAILED; public static final int HTTP_FORBIDDEN; public static final int HTTP_GATEWAY_TIMEOUT;... with indices greater than or equal to the old size are filled with null A Vector manages its elements using an internal array that is larger than the number of elements that it contains The size of this array is referred to as the Vector's capacity and can be retrieved using the capacity() method As elements are added, the Vector increases its capacity by allocating a new internal array with additional... java.io.IOException; public static java.io.DataInputStream openDataInputStream( String name) throws java.io.IOException; public static java.io.DataOutputStream openDataOutputStream( String name) throws java.io.IOException; public static java.io.InputStream openInputStream( String name) throws java.io.IOException; public static java.io.OutputStream openOutputStream( String name) throws java.io.IOException; } ContentConnection... the name of a header, its value can either be retrieved in string form using an overloaded form of getHeaderField() that accepts the header name, or decoded as a Java int or Date object using the getHeaderFieldInt() and getHeaderFieldDate methods Finally, some fields can be obtained using convenience methods such as getDate() and getExpiration() The reply data can be read from an InputStream obtained... public static final int HTTP_GONE; public static final int HTTP_INTERNAL_ERROR; public static final int HTTP_LENGTH_REQUIRED; public static final int HTTP_MOVED_PERM; public static final int HTTP_MOVED_TEMP; public static final int HTTP_MULT_CHOICE; public static final int HTTP_NO_CONTENT; public static final int HTTP_NOT_ACCEPTABLE; public static final int HTTP_NOT_AUTHORITATIVE; public static final int... delivered together in the form of a message Datagrams are not guaranteed to be delivered In addition, the order of delivery of successive datagrams does not always match the order in which they were sent Since a 389 J2ME in a Nutshell DatagramConnection deals in discrete messages, it does not have any associated input or output streams A DatagramConnection receiver is obtained by calling the Connector . from J2ME in a Nutshell 364 the content of a String, in which case an appropriate initial capacity is determined. When the size approaches the capacity, a new character array is allocated and. central enough to the Java language to be included in the java.lang package. The Java 2 version 1.3 java.util package contains 54 classes and interfaces. By contrast, the CLDC version contains. to a boolean, a char, an array of characters (char[]), an int, a long or an arbitrary Java Object. With an Object, the String is created using the return value of the object's toString()