如何在Java或PDE中打印实例的内容?

发布于 2025-01-28 22:50:28 字数 518 浏览 1 评论 0 原文

class bouncingBall():
    def __init__(self, bounce, window, position):
        self.bounce = bounce
        self.window = window
        self.position = position

ball = bouncingBall(0.35, 1.5, 0.75)
print(ball) # <__main__.bouncingBall object at 0x0000025980427D60>
print(ball.__dict__) # {'bounce': 0.35, 'window': 1.5, 'position': 0.75}

检查实例的内部?

在Python中,我们可以使用对象.__ dict __ 如何在 .java .pde

class bouncingBall():
    def __init__(self, bounce, window, position):
        self.bounce = bounce
        self.window = window
        self.position = position

ball = bouncingBall(0.35, 1.5, 0.75)
print(ball) # <__main__.bouncingBall object at 0x0000025980427D60>
print(ball.__dict__) # {'bounce': 0.35, 'window': 1.5, 'position': 0.75}

In python we can inspect the insides of an instance by using object.__dict__

How do we accomplish this in .java or .pde?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

许仙没带伞 2025-02-04 22:50:28

正如Saksham(+1)指向您的那样,一个选项是覆盖 toString():这是手动的,但没有反射的开销。

您也可以使用 java.lang.reflect。*; 您可以将其用于UTITTY功能在超级类中,您所有的子类都将继承此特征(每个子类都无需手动覆盖 toString()),但是您将花费一些CPU时间来反映。

这是一个非常粗略的示例,展示了这两个:

// option 2: reflect
import java.lang.reflect.*;

class BouncingBall{

  float bounce;
  float window;
  float position;
    
  BouncingBall(float bounce, float window, float position){
    this.bounce = bounce;
    this.window = window;
    this.position = position;
  }
  // option 1: override toString() (manual)
  String toString(){
    return String.format("[BouncingBall bounce=%.2f window=%.2f position=%.2f]", 
                                        bounce, window, position);
  }
}

void setup(){
  BouncingBall ball = new BouncingBall(0.35, 1.5, 0.75);
  println("ball properties and values via toString()");
  println(ball);
  println();
  
  println("ball properties and values via reflection");
  // reflect instance fields
  try{
    for(Field field : BouncingBall.class.getDeclaredFields()){
      println(field.getName(), field.get(ball));
    } 
  }catch(IllegalAccessException e){
    e.printStackTrace();
  }
}

更新
在Python中,很高兴您获得 dict 回来,您可以进一步使用。
在Java中,从理论上讲,您可以返回 hashmap (或类似的地图结构),但是您只能关联相同类型的键。
在这种情况下,由于所有属性都是浮动的,但是您可能会有属性是布尔人,浮点,ints等的情况。
可以使用 jsonobject https://processing.org/reference/savejsonobject_.html” serialize/将数据保存到磁盘中

import java.lang.reflect.Field;

class BouncingBall{

  float bounce;
  float window;
  float position;
    
  BouncingBall(float bounce, float window, float position){
    this.bounce = bounce;
    this.window = window;
    this.position = position;
  }
  
  // option 1: override toString() (manual)
  String toString(){
    return String.format("{\"bounce\":%.2f, \"window\":%.2f, \"position\":%.2f}", 
                             bounce, window, position);
  }
  // option 2: reflect
  JSONObject toJSON(){
    JSONObject result = new JSONObject();
    try{
      for(Field field : BouncingBall.class.getDeclaredFields()){
        // handle floats for demo purposes
        if(field.getType() == float.class){
          result.setFloat(field.getName(), (float)field.get(this));
        }
      } 
    }catch(IllegalAccessException e){
      e.printStackTrace();
    }
    return result;
  }
}

void setup(){
  BouncingBall ball = new BouncingBall(0.35, 1.5, 0.75);
  println("ball properties and values via toString()");
  println(ball);
  println();
  
  println("ball properties and values via reflection");
  println(ball.toJSON());
  
  // save JSON data
  saveJSONObject(ball.toJSON(), "ball.json");
}

通过 savestrings()

同样,您可以使用反射将加载的JSON数据映射到实例属性。

As Saksham(+1) points you, one option is to override toString(): this is manual, but it doesn't have the overhead of reflection.

You can also use java.lang.reflect.*; which you could use for a utilty function in a superclass, then all your subclasses will inherit this trait (no need to manually override toString() for each subclass), however you will spend a bit of CPU time reflecting.

Here's a very rough example demonstrating both:

// option 2: reflect
import java.lang.reflect.*;

class BouncingBall{

  float bounce;
  float window;
  float position;
    
  BouncingBall(float bounce, float window, float position){
    this.bounce = bounce;
    this.window = window;
    this.position = position;
  }
  // option 1: override toString() (manual)
  String toString(){
    return String.format("[BouncingBall bounce=%.2f window=%.2f position=%.2f]", 
                                        bounce, window, position);
  }
}

void setup(){
  BouncingBall ball = new BouncingBall(0.35, 1.5, 0.75);
  println("ball properties and values via toString()");
  println(ball);
  println();
  
  println("ball properties and values via reflection");
  // reflect instance fields
  try{
    for(Field field : BouncingBall.class.getDeclaredFields()){
      println(field.getName(), field.get(ball));
    } 
  }catch(IllegalAccessException e){
    e.printStackTrace();
  }
}

Update
In Python, it's nice you get a dict back which you can use further.
In Java, in theory you could return a HashMap (or similar Map structure), however you can only associate keys of the same type.
In this case, since all properties are float that would work, however you might have situations where the properties would be booleans, floats, ints, etc.
A workaround for this could be using JSONObject: a nice side effect of this option is you could easily serialize/save the data to disk via saveJSONObject():

import java.lang.reflect.Field;

class BouncingBall{

  float bounce;
  float window;
  float position;
    
  BouncingBall(float bounce, float window, float position){
    this.bounce = bounce;
    this.window = window;
    this.position = position;
  }
  
  // option 1: override toString() (manual)
  String toString(){
    return String.format("{\"bounce\":%.2f, \"window\":%.2f, \"position\":%.2f}", 
                             bounce, window, position);
  }
  // option 2: reflect
  JSONObject toJSON(){
    JSONObject result = new JSONObject();
    try{
      for(Field field : BouncingBall.class.getDeclaredFields()){
        // handle floats for demo purposes
        if(field.getType() == float.class){
          result.setFloat(field.getName(), (float)field.get(this));
        }
      } 
    }catch(IllegalAccessException e){
      e.printStackTrace();
    }
    return result;
  }
}

void setup(){
  BouncingBall ball = new BouncingBall(0.35, 1.5, 0.75);
  println("ball properties and values via toString()");
  println(ball);
  println();
  
  println("ball properties and values via reflection");
  println(ball.toJSON());
  
  // save JSON data
  saveJSONObject(ball.toJSON(), "ball.json");
}

(Notice the manual option of formatting toString() so the data is valid JSON also works (an can be saved to disk via saveStrings())

Similarly you could use reflection to map loaded JSON data to instance properties should you need to.

我最亲爱的 2025-02-04 22:50:28

您可以在球类中覆盖 toString 并打印实例数据
你自己。

或者,您可以使用反射
所有字段数据并打印

You can override toString in your Ball class and print the instance data
yourself.

Or you can use reflection Get the class instance variables and print their values using reflection to get
all the fields data and print it

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文