2

I have a Java class which contains fields like this:

private int port;
private String portName;
private ArrayList portList;
private int id;

I need a command or script so I can directly paste the above block in terminal and give it as input to that command or script and give me following output:

public String toString() {
    return "{ " + "port=" + port + ",portName=" + portName + ",portList=" + portList + ",id=" + id + "}";
}
4
  • So you want to implement this in Bash? Have you already tried it yourself? Should be pretty simple.
    – wjandrea
    Nov 25 '17 at 19:21
  • 2
    FWIW, you can implement this once for all classes in Java with reflection, so you don't have to rely on code generation tools. If you post a suitable question on Stack Overflow and send me a link, I'll write an answer. Nov 25 '17 at 23:13
  • 1
    You could also consider using Lombok to generate this method (and others). Once your project is set up with Lombok, all you would do is add an annotation to your class (@ToString in this case) and this method would be dynamically generated for you.
    – nickb
    Nov 26 '17 at 0:50
  • Actually I am confused, which one to choose best answer. Both wjandrea's and dessert's answer are correct. So I am thinking which one to choose. Nov 26 '17 at 10:32
3

A oneliner using awk (i.e. GNU Awk):

awk 'BEGIN{printf"public String toString() {\n    return \"{ \""}{gsub(";$","");printf" + \"";if(NR>1){printf","};printf$3"=\" + "$3}END{print" + \"}\";\n}"}'

Use it like this:

$ awk 'BEGIN{printf"public String toString() {\n    return \"{ \""}{gsub(";$","");printf" + \"";if(NR>1){printf","};printf$3"=\" + "$3}END{print" + \"}\";\n}"}' <<EOF
> private int port;
> private String portName;
> private ArrayList portList;
> private int id;
> EOF
public String toString() {
    return "{ " + "port=" + port + ",portName=" + portName + ",portList=" + portList + ",id=" + id + "}";
}

Script version with explaining commentary

#!/usr/bin/awk -f
# do the following before processing the text
BEGIN {
  # print this text, '\n' is a line break and '\"' a literal '"'
  printf "public String toString() {\n    return \"{ \""
}
{
  # remove semicolon at the end of the line
  gsub(";$","");
  # print ' + "'
  printf " + \"";
  # if the line number is > 1 print ','
  if (NR > 1) { printf "," };
  # print the third row followed by '=" + ' and the third row again
  printf $3"=\" + "$3
}
# do the following after processing the text
END {
  # print ' + "}";\n}', '\n' is a line break
  print " + \"}\";\n}"
}

Save it as e.g. generate_toString, make it executable with chmod +x generate_toString and use it like this:

$ ./generate_toString <<EOF
> private int port;
> private String portName;
> private ArrayList portList;
> private int id;
> EOF
public String toString() {
    return "{ " + "port=" + port + ",portName=" + portName + ",portList=" + portList + ",id=" + id + "}";
}

While this does what you asked for, to solve your actual problem there are far better approaches, see @DavidFoerster's as well as @nickb's comment above. There's no need to reinvent the wheel.

1
  • Thank you for answering my question. Your solution works perfectly. I especially liked the oneliner. And yes, it was actually my mistake that I forgot the '+' before last bracket. So, what you have done is correct. Nov 26 '17 at 10:23
3

I think this is what you want.

#!/bin/bash
# Create Java toString() method from stdin.

while read line; do
    word_last="${line##* }"
    name="${word_last%;}"
    if [[ $pairs ]]; then
        printf -v pair '",%s=" + %s + ' "$name" "$name"
    else
        printf -v pair '"%s=" + %s + ' "$name" "$name"
    fi
    pairs+="$pair"
done

printf '%s\n' 'public String toString() {'
printf '    return "{ " + %s"}";\n' "$pairs"
printf '%s\n' '}'

Call like this:

$ bash create_java_toString.sh << EOF
> private int port;
> private String portName;
> private ArrayList portList;
> private int id;
> EOF
public String toString() {
    return "{ " + "port=" + port + ",portName=" + portName + ",portList=" + portList + ",id=" + id + "}";
}

More examples:

$ bash create_java_toString.sh << EOF
> private int i;
> private int j;
> EOF
public String toString() {
    return "{ " + "i=" + i + ",j=" + j + "}";
}
$ bash create_java_toString.sh << EOF
> EOF
public String toString() {
    return "{ " + "}";
}
1
  • Thank you for taking your time to answer my question. Your solution works perfectly as expected. And yes I tried to do this my self, but couldn't go further than separating the fields, as I don't know much about commands. Nov 26 '17 at 9:46
1

I don't know how you intend to use these script but this should start you in the right direction:

#!/usr/bin/env bash

# get the argumetenst from the command line

# Sample terminal usage
# tostring -p port -n portName -l portLiat -i id


echo ""
echo ""

while getopts :p:n:l:i: option
do
        case "${option}" in
                p) port=${OPTARG};;
                n) portName=${OPTARG};;
                l) portList=${OPTARG};;
                i) id=${OPTARG};;
                \?) 
                        echo ""
                        echo -e "\e[0;31m Please supply the required values: $OPTARG \e[0m" 1>&2 
                        echo ""
                        echo " Usage: tostring -p port -n portName -l portList -i id"
                        echo ""
                        exit 1
                        ;;
                : )
                        echo "Invalid option $OPTARG requires an argument" 1>&2
                        ;;
        esac
done
shift $((OPTIND -1))

echo ""
echo ""

echo -e "\e[0;33m public String toString() {"
echo -e "       return "{ " + "port=" + "$port" + ",portName=" + "$portName" + ",portList=" + "$portList" + ",id=" + "$id" "}";"
echo ""
echo ""
echo -e "}"
echo -e "\e[0m"

More info:

https://sookocheff.com/post/bash/parsing-bash-script-arguments-with-shopts/

1
  • I think you have not understood the question properly. The name of fields are not fixed. They will be different for different class. Nov 26 '17 at 10:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.