Saturday, 26 July 2014

get() : Get reference object's referent

public T get()
Returns this reference object's referent. This method returns null if this reference object has been cleared.

import java.lang.ref.*;

public class GetReferent {
    static class Employee{
        String name;
        int id;

        Employee(int id, String name){
            this.id =id;
            this.name = name;
        }
        
        @Override
        public String toString(){
            return id +" " + name;
        }
    }

    public static void main(String args[]) throws InterruptedException{
        
        Employee emp1 = new Employee(1, "Krishna");
        
        WeakReference<Employee> weakRef;
        weakRef = new WeakReference<> (emp1);
        
        System.out.println(weakRef.get());
        emp1 = null;
        System.gc();
        System.out.println(weakRef.get());
        
    }
}

Output
1 Krishna
null



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment