How do I print the variable name holding an object?

前端 未结 10 1121
耶瑟儿~
耶瑟儿~ 2020-12-16 15:27

How do I print the variable name holding my object?

For example, I have:

myclass ob=new myclass()

How would I print \"ob\"?

10条回答
  •  天命终不由人
    2020-12-16 15:55

    Try reflection + hash code. E.g.:

    String hashcode = ob.hashCode();
    String obName;
    java.lang.reflect.Field[] fields = 
    ob.getClass().getDeclaredFields();
    
    for( final  java.lang.reflect.Field field : fields )
    {
      if( field.hashCode().equals(hashcode) )
      {
        obName = field.getName();
        break;
      }
    }
    System.out.println(obName);
    

提交回复
热议问题