0

Suppose i have a file and its name is file.txt It consists of scripts for the reflection method in java. Suppose some of it are:

new <id> <class> <arg0> <arg1> … creates a new instance of <class> by using 
a constructor that takes the given argument types and stores the result in <id>.
call <id> <method> <arg0> <arg1> …  invokes the specified <method> that 
takes the given arguments on the instance specified by <id> and prints the answer. 
print <id>  prints detailed information about the instance specified by <id>. See 
below for Object details.

The script from the file would be picked up as string in the program. How will i convert it to the arguments i specified above for reflection. Am blind on this one! a bit description with some code help would be appreciated as am new to java.

1 Answer 1

1

This is a matter of parsing, first of all. The first thing you need to do is break your input up into manageable chunks. Since you seem to be using whitespace to separate your components, that should be a fairly easy matter.

Since you have one command per line, the first thing you would do is break them up into lines, and then into separate strings based on whitespace. Parsing is a large enough topic to deserve it's own question.

Then you would go line by line, use if statements on the first word in the line to determine what command should be executed, then parse the other words based on what is being done with them.

Something like this:

public void execute(List<String> lines){
    for(String line : lines){
        // This is a very simple way to perform the splitting. 
        // You may need to write more code based on your needs.
        String[] parts = lines.split(" ");

        if(parts[0].equalsIgnoreCase("new")){
            String id = parts[1];
            String className = parts[2];
            // Etc...
        } else if(parts[0].equalsIgnoreCase("call")){
            String id = parts[1];
            String methodName = parts[2];
            // Etc...
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.