System.out.println("Cloning not allowed.");
return this;
}
}
}
class CloneDemo2 {
public static void main(String args[]) {
TestClone x1 = new TestClone();
TestClone x2;
x1.a = 10;
x1.b = 20.98;
// here, clone() is called directly.
x2 = (TestClone) x1.clone();
System.out.println("x1: " + x1.a + " " + x1.b);
System.out.println("x2: " + x2.a + " " + x2.b);
}
}
The side effects caused by cloning are sometimes difficult to see at first. It is easy to
think that a class is safe for cloning when it actually is not. In general, you should not
implementCloneablefor any class without good reason.
Class
Classencapsulates the run-time state of an object or interface. Objects of typeClassare
created automatically, when classes are loaded. You cannot explicitly declare aClassobject.
Generally, you obtain aClassobject by calling thegetClass( )method defined byObject.
Classis a generic type that is declared as shown here:
class Class<T>
Here,Tis the type of the class or interface represented. A sampling of commonly used methods
defined byClassis shown in Table 16-15.
Chapter 16: Exploring java.lang 415
Method Description
static Class<?> forName(Stringname)
throws ClassNotFoundException
Returns aClassobject given its complete name.
static Class<?> forName(Stringname,
booleanhow,
ClassLoaderldr)
throws ClassNotFoundException
Returns aClassobject given its complete name.
The object is loaded using the loader specified by
ldr.Ifhowistrue, the object is initialized;
other wise, it is not.
<A extends Annotation> A
getAnnotation(Class<A>annoType)
Returns anAnnotationobject that contains the
annotation associated withannoTypefor the
invoking object.
TABLE 16-15 A Sampling of Methods Defined byClass