Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to translate a java object to a map in clojure?

Tags:

java

clojure

For example:

class Person {
    String name;
}

I would like to get {:name "xxx} from an instance of Person.

I know (from_json (.toJson person)) can do it.

Is there any better way to achieve it?

like image 751
user2219372 Avatar asked Jun 11 '26 01:06

user2219372


1 Answers

Have you seen the bean function? The example code above doesn't follow the JavaBean rules, but if your objects do (using getters), then bean will turn it into a Clojure map for you.

public class Person {
  private String name;
  public Person(String n) {
    this.name = n;
  }
  public String getName() {
    return name;
  }
}

Use like this:

(def p (Person. "xyz"))
(bean p)
;=> {:name "xyz" :class Person}
like image 178
Alex Miller Avatar answered Jun 14 '26 04:06

Alex Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!