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中,我們可以通過使用檢查實體的內部object.__dict__
我們如何在.javaor中實作這一點.pde?
uj5u.com熱心網友回復:
正如 Saksham( 1) 指出的那樣,一種選擇是覆寫toString():這是手動的,但它沒有反射的開銷。
你也可以使用java.lang.reflect.*; 您可以將其用于超類中的實用函式,然后您的所有子類都將繼承此特征(無需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(或類似的 Map 結構),但是您只能關聯相同型別的鍵。在這種情況下,由于所有屬性都是可以作業的浮點數,但是您可能會遇到屬性為布林值、浮點數、整數等的情況。解決此問題的方法可能是使用JSONObject:此選項的一個很好的副作用是您可以通過以下方式輕松序列化/保存資料到磁盤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");
}
(請注意格式化 toString() 的手動選項,以便資料有效 JSON 也可以作業(可以通過 保存到磁盤saveStrings())
同樣,如果需要,您可以使用反射將加載的 JSON 資料映射到實體屬性。
uj5u.com熱心網友回復:
您可以toString在 Ball 類中覆寫并自己列印實體資料。
或者可以使用反射獲取類實體變數并列印它們的值使用反射獲取所有欄位資料并列印
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/474899.html
下一篇:如何在控制臺中輸出字符影像
