Require a java program to create method templates - java

I have a text file which contains the list of all public method names. I require a Java program which reads each method name from the text file and create a method(template) for each public method name.
Say,
My text file contains, 3 methods
public static void A()
public static void B()
public static void C()
I need a output like this.
public class class_name
{
public void A_test()
{
System.out.println("Method A");
}
public void B_test()
{
System.out.println("Method B");
}
public void C_test()
{
System.out.println("Method C");
}
}
Kindly give your suggestions.

Following your example above the code below will generate a similar output. Note there is no package. NOTE As your example the generator strips static
public class ClassBuilder
{
public static String buildClass(String className,ArrayList<String> methods)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(String.format("public class %s \n{", className)).append("\n");
for (String method: methods)
{
stringBuilder.append(String.format(" %s \n {", method.trim().replace("static ","").replace("()","_test()"))).append("\n }\n\n");
}
stringBuilder.append("}");
return stringBuilder.toString();
}
public static void main(String[] args)
{
Scanner scanner = null;
try
{
scanner = new Scanner(new File("d:\\testFile.txt"));
ArrayList<String> methods = new ArrayList<String>();
while (scanner.hasNext())
{
methods.add(scanner.nextLine());
}
scanner.close();
String javaClass = buildClass("className", methods);
System.out.println(javaClass);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
output
public class className
{
public void A_test()
{
}
public void B_test()
{
}
public void C_test()
{
}
}

Related

in java multi-catch every multi-catch character is final, but I'm not able to get it

class Main
{
public static void main(String args[])
{
try{
throw new ArrayIndexOutOfBoundsException("yyyoyo");
}
catch(ArrayIndexOutOfBoundsException |ArithmeticException e)
{
e.initCause(new Exception());
}
}
}
As we know that multi-catch parameter is implicitly final, so how I'm able to chain an exception in the catch block.
A final reference means you can not assign a new value to it. It does not stop the object from being updated.
For example:
class MyClass {
String string;
public MyClass(String string) {
super();
this.string = string;
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
#Override
public String toString() {
return "MyClass [string=" + string + "]";
}
}
public class Main {
public static void main(String[] args) {
final MyClass obj = new MyClass("Test");
System.out.println(obj);
obj.setString("Testing");
System.out.println(obj);
// obj= new MyClass("Testing"); // Trying to assign a new value to obj will result in a compilation error
}
}
Output:
MyClass [string=Test]
MyClass [string=Testing]

Strategy pattern to read different file formats

public interface FileReader {
void readFile();
void writeFile();
}
public class XMLReader implements FileReader {
#Override
public void readFile() {
System.out.println("Hellp i am read");
}
#Override
public void writeFile() {
System.out.println("Hello i am write");
}
}
public class ExcelReader implements FileReader {
#Override
public void readFile() {
System.out.println("Hellp i am read");
}
#Override
public void writeFile() {
System.out.println("Hello i am write");
}
}
public class Context {
FileReader reader ;
public Context(FileReader reader) {
super();
this.reader = reader;
}
public void executeRead(){
reader.readFile();
}
}
public class TestStrategy {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(args[0]);
String s=args[0];
String[] a=s.split("\\.");
if(a[1].equals("csv")){
new Context(new XMLReader()).executeRead();
}else{
new Context(new ExcelReader()).executeRead();
}
}
}
I have a concern more file format are introduced we will create separate class for them but i have to change the if else code in TestStrategy class to create new object for the file pattern introduced.
Can we remove this if else code .Any suggestions.
You could use a registry that maps a files extension to the implementation.
public class Registry {
static Map<String,FileReader> reg = new HashMap<String,FileReader>();
public static void register(String ext, FileReader fr ) {
reg.put( ext, fr );
}
}
and let newly added implementation register themself e.g.
public class XMLReader implements FileReader {
static {
Registry.register( "xml", new XMLReader() );
}
....
public class ExcelReader implements FileReader {
static {
Registry.register( "xls", new ExcelReader() );
}
...
then you could simply lookup the registry for a suitable implementation with no if or switch required.
You can get a class by name. Build a Map to configure the FileReader to use for each extension.
public static void main(String[] args)
throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Map<String, String> extensionToClass = new HashMap<>();
extensionToClass.put("xml", "de.lhorn.XMLReader");
extensionToClass.put("xls", "de.lhorn.ExcelReader");
String s = "foo.xml";
String[] a = s.split("\\.");
String extension = a[1];
// Get the class that is configured for the extension.
String className = extensionToClass.get(extension);
Class clazz = Class.forName(className);
// Create a new instance of this class.
FileReader reader = (FileReader) clazz.newInstance();
// Use the FileReader.
new Context(reader).executeRead();
}
You can read extensionToClass from an external source, of course.

How to use method showMessage()?

In class we learned about methods, but I'm having a bit of trouble using them.
In a package called util, I wrote a class called IO.
public class IO {
public static float getFloat(){
String str = JOptionPane.showInputDialog("Enter a real number");
return Float.parseFloat(str);
}
public static void showMessage(Scanner s){
System.out.println(s);
JOptionPane.showMessageDialog(null, s);
}
public static Scanner getInput (String prompt){
String s = JOptionPane.showInputDialog(prompt);
return new Scanner(s);
}
}
Also in package util, I have my program, called Program 4.
public class Program4 {
public static void main(String[] args) {
IO.getInput("enter 2 integers");
IO.showMessage(Scanner(s));
}
}
What I don't understand is how do I display the 2 integers entered? One is a scanner object and one is string. How do I use the method getInput to show convert the scanner into a string? Am I going to have to write a new method and use parse?
You can get user input without using Scanner. Here is example:
IO Class
public class IO {
public static float getFloat() {
String str = JOptionPane.showInputDialog("Enter a real number");
return Float.parseFloat(str);
}
public static void showMessage(String s) {
System.out.println(s);
JOptionPane.showMessageDialog(null, s);
}
public static String getInput(String prompt) {
// JOptionPane.showInputDialog() return user input String
String input = JOptionPane.showInputDialog(prompt);
return input;
}
}
Program4 Class
public class Program4 {
public static void main(String[] args) {
// IO.getInput() return stored input String
String input = IO.getInput("enter 2 integers");
IO.showMessage(input);
}
}

How to generically implement calling methods stored in a HashMap?

I want to route certain chars to methods, so that when the char is typed in the command-line the method is then executed.
Based on the answer How to call a method stored in a HashMap, I'm mapping these chars to methods by using the "Command" design-pattern.
However I want to generically implement this, so it seems that I need to implement reflection in order to use the Method class as a parameter. My attempt is getting a NullPointerException on the field private Method method in my anonymous class...
Here is my code:
import java.lang.reflect.Method;
public interface InvokesMethod {
public void invokeMethod() throws Exception;
public void setMethod(Method method);
} // end of interface
import java.util.HashMap;
import java.lang.reflect.Method;
public class Terminal {
public HashMap<Character, InvokesMethod> commands;
public Terminal() {
this.commands = new HashMap<Character, InvokesMethod>();
try {
this.setCommand('p',
this.getClass().getDeclaredMethod("printHelloWorld"));
} catch (Exception e) {
e.printStackTrace();
}
}
private void printHelloWorld() {
System.out.println("Hello World!");
}
private void setCommand(char letter, Method method) {
this.commands.put(letter, new InvokesMethod() {
// NullPointerException starts here in the stack-trace:
private Method method;
#Override
public void invokeMethod() throws Exception {
method.invoke(null);
}
#Override
public void setMethod(Method method) {
this.method = method;
}
}).setMethod(method);
}
public void executeCommand(char letter) throws Exception {
this.commands.get(letter).invokeMethod();
}
} // end of class
public class Main() {
public static void main(String[] args) {
Terminal commandLine = new Terminal();
try {
commandLine.executeCommand('p');
} catch (Exception e) {
e.printStackTrace();
}
}
} // end of class
Regards to your code you didn't initiate method. Bear in mind that execute with null you must call public static method:
Your other issue , you didn't initiated interface properly. Here is working example:
InvokesMethodItf
public interface InvokesMethodItf {
public void invokeMethod() throws Exception;
public void setMethod(Method method);
}
InvokesMethod
public class InvokesMethod implements InvokesMethodItf{
private Method method;
#Override
public void invokeMethod() throws Exception {
method.invoke(null);
}
#Override
public void setMethod(Method method) {
this.method = method;
}
}
Terminal
public class Terminal {
public HashMap<Character, InvokesMethodItf> commands;
public Terminal() {
this.commands = new HashMap<Character, InvokesMethodItf>();
try {
this.setCommand('p',
this.getClass().getDeclaredMethod("printHelloWorld"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void printHelloWorld() {// method.invoke(null) looking for "static" method
System.out.println("Hello World!");
}
private void setCommand(char letter, Method method) {
InvokesMethodItf inv = new InvokesMethod();
inv.setMethod(method);
this.commands.put(letter, inv);
}
public void executeCommand(char letter) throws Exception {
this.commands.get(letter).invokeMethod();
}
}
Main
public class Main {
public static void main(String[] args) {
Terminal commandLine = new Terminal();
try {
commandLine.executeCommand('p');
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Hello World!
Thanks to #Maxim's original suggestion here, I have an alternate solution by setting the methods as Strings in the HashMap instead --
import java.util.HashMap;
import java.lang.reflect.Method;
public class Terminal {
private HashMap<Character, String> commands;
public Terminal() {
this.commands = new HashMap<Character, String>();
this.commands.put('p', "printHelloWorld");
}
private void printHelloWorld() {
System.out.println("Hello World!");
}
public void executeCommand(char letter) throws Exception {
Method method = getClass().getDeclaredMethod(this.commands.get(letter));
method.invoke(this);
}
public class Main {
public static void main(String[] args) {
Terminal commandLine = new Terminal();
try {
commandLine.executeCommand('p');
} catch (Exception e) {
e.printStackTrace();
}
}
} // end of class
Output:
Hello World!
Now to figure out how to pass parameters to the reflected methods...

Java reflection when a method has a variable arglist

I've got something along the lines of the following:
public class A {
public void theMethod(Object arg1) {
// do some stuff with a single argument
}
}
public class B {
public void reflectingMethod(Object arg) {
Method method = A.class.getMethod("theMethod", Object.class);
method.invoke(new A(), arg);
}
}
How do I modify that so that I can do the following instead?
public class A {
public void theMethod(Object... args) {
// do some stuff with a list of arguments
}
}
public class B {
public void reflectingMethod(Object... args) {
Method method = A.class.getMethod("theMethod", /* what goes here ? */);
method.invoke(new A(), args);
}
}
A.class.getMethod("theMethod", Object[].class);
Darthenius's suggestion in the comments for the original question worked, once I wrapped my head around how to do it.
public class A {
public void theMethod(ArrayList<Object> args) { // do stuff
}
}
public class B {
public void reflectingMethod(ArrayList<Object> args) {
Method method;
try {
method = A.class.getMethod("theMethod", args.getClass());
method.invoke(new A(), args);
} catch (Exception e) {}
}
}

Categories

Resources