Java reflection
Class object:
Objects derived from a new class are also instance objects.
Class objects:
A product of class loading that encapsulates all information about a class (class name, superclass, excuses, attributes, methods, constructors)
Get class object:
Get the class object from the class object:
Student s = new Student();
Class c = s.getClass();
Copy the code
Get the class object by class name:
Class c = Class name. Class; * Class c = class.forname (" package name. The name of the class "); ** Public String getName() public Package getPackage() public Class<? SuperT > getSuperclass() public <? >[] getInterfaces() public Field[] getFields() public Method[] getMethods() public Construcotor<? < p style = "max-width: 100%; clear: both; min-height: 1em; II. Factory mode is mainly responsible for creating problems. III. Factory mode can be designed through reflection to complete the creation of dynamic objects.Copy the code
// factory ---- The factory where the object is created
public static Object createObject(String className) {
try {
Class c = Class.forName(className);
return c.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return null; }}Copy the code
Singleton: Only one object of this class is allowed to be created. Method 1: Hacks (created while class loading, naturally thread-safe)
// Hungry: naturally thread-safe (no lock), created when the class is loaded (created when not in use, taking up resources)
class Singleton{
private static final Singleton instance = new Singleton();
private Singleton(a) {}
public static Singleton getInstance(a) {
returninstance; }}Copy the code
Method 2: lazy (create while using, thread unsafe, add synchronization)
// Lazy: created when used, inherently thread unsafe (with synchronization lock); Low efficiency
class Singleton{
private static Singleton instance = null;
private Singleton(a) {}
public static Singleton getInstance(a) {
if(instance == null) {
instance = new Singleton();
}
returninstance; }}Copy the code
Option 3: Lazy (created while in use, thread-safe)
// Lazy, created when used, naturally thread safe
class Singleton{
private Singleton(a) {}
private static class Holder{
static final Singleton instance = new Singleton();
}
public static Singleton getInstance(a) {
returnHolder.instance; }}Copy the code