-3

-When I use toString to print: System.out.println(animal);

  • I get this : Animal{name='Shark', weight=30, speed=40}
  • What I want is : Animal {name = 'Shark', weight = 30, speed = 40}.
  • How I can force I-IDEA make what I want automatically?
Tu Le Anh
  • 91
  • 1
  • 7
  • 4
    You can override `toString()` method for `Animal` class to return whatever kind of string you want. – Rohan Kumar Mar 01 '21 at 12:49
  • And i want toString generate automatically. – Tu Le Anh Mar 01 '21 at 12:50
  • The only way is the one that @RohanKumar said. You can't do it automatically if you do not override toString(). – Doch88 Mar 01 '21 at 12:51
  • 1
    It is not "Java" doing that, at least not through JDK 11 it isn't. Maybe it's your IDE trying to "help". In any case, you have two choices: write your own ToString, or fix whatever's providing the toString for you. – user15187356 Mar 01 '21 at 12:52
  • 1
    The duplicate is wrong. This is not about getting Class instead of content. This is about formatting. @TuLeAnh there is no nice way to do this I can think of. 1) Override as stated but loop the properties to have it apply for different content. 2) Do a regex replace on word boundaries (\b) with space \b space. You will need capture groups for that: https://stackoverflow.com/questions/7630707/regular-expression-replace-but-keep-part-of-the-string –  Mar 01 '21 at 13:06
  • @LarsWissler I don't understand how the duplicate is wrong. The answer is simple: override `toString()`, I can reopen this question. But unless OP doesn't specify what they mean with *generate automatically* it will just get closed as unclear instead – Lino Mar 01 '21 at 15:02
  • @TuLeAnh what are you meaning exactly with generate automatically? Are you looking for something like [Lombok `@ToString`](https://projectlombok.org/features/ToString)? – Lino Mar 01 '21 at 15:07
  • @Lino Ok, I may be completely wrong, but as I understood the question it is about generic formatting. I mean the question is bad because no context about animal is provided. If it were a normal class the output would be Class@something as in the marked duplicate. Here it looks like an JSONObject or something like that and the issue is a generic output applicable to any nesting with added spaces between the seperators. –  Mar 01 '21 at 16:04
  • @Lino this question about formatting, i want when i create toString it will be " Animal {name = 'Shark', weight = 30, speed = 40}. " automatically, not "Animal{name='Shark', weight=30, speed=40}". And i dont want to edit when override, it must automatic. – Tu Le Anh Mar 02 '21 at 14:37

1 Answers1

-1

You can generate toString() method and edit that