Java的.lang.ref.Reference类在Java中
Java.lang.ref.Reference Class 是引用对象的抽象基类。此类包含用于获取有关参考对象的信息的方法。此类不是直接子类,因为对引用对象的操作与垃圾收集器密切合作。
类声明:防止
public abstract class Reference
extends Object
方法:Method Description clear() This method prevents this object from being enqueued by clearing this reference object. Only java code can invoke this method. The garbage collector can directly clear references. The garbage collector doesn’t need to invoke this method for clearing references. enqueue() This method adds this object to its registered queue. get() This method is used to get the object to which this reference refers. It returns null if either java code or garbage collector cleared the object at this reference. isEnqueued() This method is used to know if this reference object is registered with any queue or not.
1. public void clear():
此方法通过清除此引用对象来防止此对象入队。只有Java代码可以调用这个方法。垃圾收集器可以直接清除引用。垃圾收集器不需要调用此方法来清除引用。
2. public boolean enqueue() :
此方法将此对象添加到其注册队列。
返回:如果此引用对象已成功添加到已注册的队列中,则返回 true;如果此引用对象在创建时未在任何队列中注册,则返回 false。
3.公共T get():
此方法用于获取此引用所引用的对象。如果Java代码或垃圾收集器清除了此引用处的对象,则返回 null。
返回:此引用所引用的对象,如果对象已被清除,则返回null。
4. public boolean isEnqueued():
此方法用于知道此引用对象是否已注册到任何队列。
返回:如果此引用对象已入队,则为真,否则为假
Java
// Java program to illustrate working of Reference Class
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
class Gfg {
}
public class GFG {
public static void main(String[] args)
{
// Strong Reference
Gfg g = new Gfg();
ReferenceQueue q = new ReferenceQueue();
// Creating Soft Reference to Gfg-type object to
// which 'g' is also pointing and registering it
// with q
Reference softref
= new SoftReference(g, q);
g = softref.get();
System.out.println(g.toString());
// enqueue softref to its rregistered queue i.e q
if (softref.enqueue()) {
System.out.println(
"Object successfully enqueued");
}
else {
System.out.println("Object not enqueued");
}
// checking if softref is enqueued or not
if (softref.isEnqueued()) {
System.out.println("Object is enqueued");
}
else {
System.out.println("Object not enqueued");
}
// clearing this reference object
softref.clear();
System.out.println("Object cleared");
// trying to enqueue after clearing
if (softref.enqueue()) {
System.out.println(
"Object successfully enqueued");
}
else {
System.out.println("Object not enqueued");
}
}
}
Gfg@214c265e
Object successfully enqueued
Object is enqueued
Object cleared
Object not enqueued