basically am trying to make java command prompt. Suppose user enters as input from the user:
new x java.util.ArrayList
here x is the object name and java.util.ArrayList is the class. So this script inputed by the user means create an object of class java.util.ArrayList.
Now suppose that user enter:
new x java.util.ArrayList int:5
means create an object x of the java.util.ArrayList and make its size 5. Like this i want that everytime i input something related to object creation as input i should be able to create class its object and its method based on the input that the user does. Am new to java and reflection so kindly help! here is the code i thought so far using my mind:
public static void token_classification() throws ClassNotFoundException
{
my_hash = new HashMap();
Keep_Obj_Info = new HashMap();
if(expression_keeper[0].equalsIgnoreCase("new"))
{
my_hash.put("Object", expression_keeper[1]);
Class Obj= Class.forName(expression_keeper[2]);
Keep_Obj_Info.put("Modifier", Obj.getModifiers());
Keep_Obj_Info.put("Package",Obj.getPackage());
////????
Constructor[] constructors = Obj.getConstructors();
}
else
if(expression_keeper[0].equalsIgnoreCase("call"))
{
}
else
if(expression_keeper[0].equalsIgnoreCase("print"))
{
}
else
{
System.out.println("Invalid Script!");
}
}
ExpressionKeeper is basically a String array that keeps the user input in tokenized form. Meaning anything next to a white space to a new location.
Well for Object creation in java; the constructor and it's arguments are required.
you can have a generic framework which will accept input from command prompt and interpret them means find out the data type of the input ex : number/string/char/boolean etc..
Also your framework should know the argument index for example say a constructor has 2 parameter and one is string and another is int. and say first parameter is int and 2nd parameter is String and while passing the parameter from the command line the user first pass string and then int in that scenario your program should be smart enough to properly arrange them in order. So many such things you need to take care of....Now coming to the example which you have mentioned for ArrayList you can write a program as follows : (I have just given you a pseudocode you can implement your own way)
{
int howManyParametersFromCommandLine = getnoParameterCount; //it will maintain no.of parameters passed from command line
String[] parametersFromCommandLine = getParametersFromcommandLine(); // Ex : {1,"ABC",new Double(80.0d)};
List<Class> parameterTypesList = parseParameters(parametersFromCommandLine); //This will identify type of each of the parameter
Class clazz = Class.forName("youClassName");
Constructor[] cons = clazz.getConstructors();
for(Constructor c : cons)
{
Class[] parameterTypes = c.getParameterTypes();
if(parameterTypes.length == howManyParametersFromCommandLine)
{
//try to match the parameter type in parameterTypesList with parameterTypes if this matches then
boolean typeMatchingAndSequecneSucess = matchParameters(parameterTypes,parameterTypesList);
if(typeMatchingAndSequecneSucess)
{
if(c.isAccessible())
{
Object[] initargs = parseAndRetActualParamValue(parametersFromCommandLine);
return c.newInstance(initargs);
}
}
}
}
}
Hope this will help you !!
You may want to use the Interpreter design pattern. It is used just for that.
The Interpreter is a bit complex, but will ensure you code interpretation works right. Also, it gives you a easy inclusion of new commands.
Take a look at here: http://en.wikipedia.org/wiki/Interpreter_pattern
Hope I could help.
Related
I am trying to create a public instance method that takes no arguments and returns no values. It is required to get an input from a user to select a file, this part I have no issues with. The method needs to make use of the BufferReader and Scanner Objects. So that it can read the file selected. For each line that is read, a new object should be created and its instance variables set using the values found in the file.
That object that is created should then be added to a list. This is where I am having issues, it won't let me add the new object to the list. Below is my code:
public void readInEntrants()
{
String pathname = OUFileChooser.getFilename();
File aFile = new File(pathname);
Scanner bufferedScanner = null;
Set<Entrant> entrantSet = new HashSet<>();
try
{
String currentEntrantLine;
Scanner lineScanner;
bufferedScanner = new Scanner(new BufferedReader(new FileReader(aFile)));
while (bufferedScanner.hasNextLine())
{
currentEntrantLine = bufferedScanner.nextLine();
lineScanner = new Scanner(currentEntrantLine);
lineScanner.useDelimiter(" ");
currentEntrantLine = lineScanner.next();
entrantSet.add(new Entrant(currentEntrantLine)); // <----- Here is where I am having trouble. It won't let me add the new object to the class Entrant
}
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
finally
{
try
{
bufferedScanner.close();
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
}
return entrantSet;
}
I'm not sure what to do. Could anyone see what I am doing wrong?
Sorry for got to add that it is a compilation issue, it will not compile properly.
Use an IDE ,I bet you dont (otherwise it would mark compilation error immediatly with red -> you use return in void method ) and in this case you would see other errors.
(off: this would go to comment section however under 50reputation I am not allowed to do that. Stackoverflow should change this imo. )
First of all:
You marked function readInEntrants as public void so you can't use return inside.
You could either remove return entrantSet; instruction or change function definition to public Set<Entrant> readInEntrants.
Concerning problem you have:
Basing on comment you left on beatrice answer I think you have only parameterless constructor for 'Entrant' class, while you try to create it passing string as parameter.
new Entrant(currentEntrantLine)
What you need to do is define Entrant class constructor that accept String as it's argument. For example:
public Entrant(String dataToParse)
{
// here you parse data from string to entrant fields
}
On the side:
You use bufferedReader to read entire file line at once and that's ok, but then you define Scanner lineScanner to iterate through line elements and then use it only once.
This way for file... let's say:
One Two Three
Four Five Six
Your while loop would work like this:
Store "One Two Three" inside currentEntrantLine.
Create scanner that'll work on "One Two Three", and set it to use space as delimiter.
Use .next to "Finds and returns the next complete token" (see documentation) and then store value inside currentEntrantLine. This way contents of currentEntrantLine is "One". Not entire line.
In next iteration you would have scanner working on "Four Five Six" and "Four" as currentEntranceLine content.
It seems the constructor of entrant class does not have any argument. Pass String as an argument type in the constructor to set the String field inside the Entrant class .
I'm working on this program which takes input from user in form of "new id class arg0 arg1 …" (e.g. new obj1 String int:5 bool:true ...). After parsing this command, i need to create a new instance of the specified class and call its constructor with the "specified arguments". Now this is the part I've been stuck in, because all the examples i saw are like constructor.newInstance(String.class, bool.class) but in my case i'm getting the arguments in form of strings and i'm confused in how to convert them to that above form and call that specific constructor. Number of arguments are also not clear, so is there any easy solution to my problem? (making instance of the given class and calling constructor with the specified number of arguments)
An example command and the action i need to perform is:
new x java.util.ArrayList int:5 --> x refers to “new ArrayList(5)”
Once you have successfully parsed your string, you can use either the Class.getConstructor() or Class.getDeclaredConstructor() to fetch the constructor you want. The main difference between those two methods for your case is that Class.getDeclaredConstructor() will also allow you to call private constructors (anything declared in the source code, hence the name). Here is an example of your test case:
int argListLength = 1; // This should really be the number of parsed arguments
Class[] argumentTypes = new Class[argListLength];
Object[] argumentValues = new Object[argListLength];
// In reality you will want to do the following statement in a loop
// based on the parsed types
argumentTypes[0] = Integer.TYPE;
// In reality you will want to do the following statement in a loop
// based on the parsed values
argumentValues[0] = 5;
Constructor<ArrayList> constructor = null;
try {
consrtuctor = java.util.ArrayList.class.getConstructor(argumentTypes);
} catch(NoSuchMethodException ex) {
System.err.println("Unable to find selected constructor..."); // Display an error
// return or continue would be nice here
}
ArrayList x = null;
try {
x = constructor.newInstance(argumentValues);
} catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
System.err.println("Unable to call selected constructor..."); // Display an error
// return or continue would be nice here
}
You may notice that there are a lot of things that can go wrong when calling a constructor. The only special one is InvocationTargetException, which wraps an exception that the successfully invoked constructor threw.
I have a varargs method and I want to call the method using 1 or 0 arguments.
The following code compiles, but does not run correctly:
final List<MyMessage> allMessages = new ArrayList<MyMessage>();
MyMessage message = null;
if (checkSomeCondition()) {
message = new MyMessage(someParam);
allMessages.add(message);
}
int size = allMessages.size();
MyMessage[] msgArrayType = new MyMessage[size]; // ERROR
MyMessage[] msgArray = allMessages.toArray(msgArrayType);
callFunc(msgArray);
...........
public void callFunc(MyMessage... messages) {
}
When I debug the code, after the line that I marked with //ERROR, the value of the array msgArrayType is com.sun.jdi.ClassNotLoadedException: Type has not been loaded occurred while retrieving component type of array.
This is also wrong:
MyMessage[] msgArray = (MyMessage[]) allMessages.toArray();
// -> java.lang.Object cannot be cast to .......MyMessage
I really don't understand it, because allMessages is a List of MyMessages!
The only option I see is to use something like
if (message == null) {
callFunc();
} else {
callFunc(message);
}
but I was wondering how the code would look like if I want to write callFunc only once. Any suggestions?
If you want to use varargs, which excepts an array - you should also make sure that the elements passed are non null.
So if you just want to use one function call of callfunc() and don't want to surround with if-else block you can use the following function call.
callfunc(message == null ? (Object)null : message);
This will either pass in the message object wrapped in array, or it will pass an array with single null element.
This is my class reponsible for new item entries, and from the start it has been a complete nightmare, I can't seem to resolve the issues I am facing which are:
setStock(float) in Item cannot be applied to ()
Item entry:
private void writeItemRecord()
{
// Check to see if we can connect to database table
if ( DataBaseHandler.makeConnectionToitemDB() == -1)
{
JOptionPane.showMessageDialog (frame, "Unable to connect to database table (Item)");
}
else // Ok, so first read data from the text fields
{
// Read data from form and store data
String Itemname = ItemnameTxtField.getText();
String Itemcode = ItemcodeTxtField.getText();
String Description = DescriptionTxtField.getText();
String Unitprice = UnitpriceTxtField.getText();
String Style = StyleTxtField.getText();
String Finish = FinishTxtField.getText();
String Stock = StockTxtField.getText();
// Convert priceStr to a float
Float fvar = Float.valueOf(Unitprice);
float price = fvar.floatValue();
Float svar = Float.valueOf(Stock);
float stock = svar.floatValue();
// Create a Item oject
Item Item = new Item();
// Set the attributes for the Item object
Item.setItemname (Itemname);
Item.setItemcode (Itemcode);
Item.setDescription (Description);
Item.setUnitprice (price);
Item.setStock(stock);
Item.setStyle(Style);
Item.setFinish(Finish);
// Write Item record. Method writeToItemTable() returns
// 0 of OK writing record, -1 if there is a problem. I store
// the returned value in a variable called error.
int error = DataBaseHandler.writeToItemTable(Item.getItemname(),
Item.getItemcode(),
Item.getDescription(),
Item.getUnitprice(),
Item.setStock(),
Item.setStyle(Style),
Item.setFinish(Finish),
Item.setSuppliercode(Suppliercode),
Item.setSuppliername(Suppliername),
Item.setAddress(Address)
);
// Check if there is a problem writing the record, in
// which case error will contain -1
if (error == -1)
{
JOptionPane.showMessageDialog (frame, "Problem writing record to Item Table");
}
// Clear the form - actual method is coded below
clearForm();
// Close database connection. Report an error message
// if there is a problem.
if ( DataBaseHandler.closeConnection() == -1 )
{
JOptionPane.showMessageDialog (frame, "Problem closing data base conection");
}
}
} // End
Any help is much appreciated!
And item extracts:
public void setStock(float StockIn)
{
Stock = StockIn;
}
public float getStock()
{
return Stock;
}
For starters, adhere to Java naming conventions. Nothing except class/interface names is allowed to use CamelCase. Use lowerCamelCase. As for your "problem", you wrote
Item.setStock(),
so obviously it's giving you the error. It is also giving you the exact line number of the error, something that would obviously have helped us to diagnose your problem.
Solution: use Item.getStock() (i suppose, it's hard to tell). Calling Item.setStock at that position (as an argument to a method call) is meaningless anyway, given that setStock is a void method.
Java compiler errors come with a line number - pay attention to it. This is your problem:
Item.setStock()
setStock() requires a parameter, you are trying to call it without one. Perhaps you meant getStock()? And I suspect that all the calls to set methods in the parameter list to writeToItemTable are also wrong, as those set methods will have void as return value, so you can't use them that way.
The setStock method looks like this:
public void setStock(float StockIn)
To call it, you need to pass a float as an argument. Somewhere in your code, you call the method, like this:
Item.setStock(),
The method needs to be called with the float argument, but instead it's called with none, hence you see a compilation error.
In this code:
int error = DataBaseHandler.writeToItemTable(Item.getItemname(),
Item.getItemcode(),
Item.getDescription(),
Item.getUnitprice(),
// Right here --> Item.setStock(),
Item.setStyle(Style),
Item.setFinish(Finish),
Item.setSuppliercode(Suppliercode),
Item.setSuppliername(Suppliername),
Item.setAddress(Address)
);
Notice that you're calling Item.setStock(), Item.setStyle(Style), etc. instead of Item.getStock(), Item.getStyle(), etc. This is probably the source of your problem - you're trying to call the setStock() method with no arguments, hence the error.
Hope this helps!
This line
// Create a Item oject
Item Item = new Item();
Is problematic. Not only is it bad style in Java to use uppercase names for variables, this particular instance results in a compile error. Also, you're calling setStock without a parameter. You need to fix that as well.
Here is your error:
int error = DataBaseHandler.writeToItemTable(Item.getItemname(),
Item.getItemcode(),
Item.getDescription(),
Item.getUnitprice(),
Item.setStock(), // <<< here! should be getStock()
Item.setStyle(Style),
Item.setFinish(Finish),
Item.setSuppliercode(Suppliercode),
Item.setSuppliername(Suppliername),
Item.setAddress(Address));
But again... consider naming/coding conventions.
Here's the situation :
I have 3 objects all named **List and I have a method with a String parameter;
gameList = new StringBuffer();
appsList = new StringBuffer();
movieList = new StringBuffer();
public void fetchData(String category) {
URL url = null;
BufferedReader input;
gameList.delete(0, gameList.length());
Is there a way to do something like the following :
public void fetchData(String category) {
URL url = null;
BufferedReader input;
"category"List.delete(0, gameList.length());
, so I can choose which of the lists to be used based on the String parameter?
I suggest you create a HashMap<String, StringBuffer> and use that:
map = new HashMap<String, StringBuffer>();
map.put("game", new StringBuffer());
map.put("apps", new StringBuffer());
map.put("movie", new StringBuffer());
...
public void fetchData(String category) {
StringBuffer buffer = map.get(category);
if (buffer == null) {
// No such category. Throw an exception?
} else {
// Do whatever you need to
}
}
If the lists are fields of your object - yes, using reflection:
Field field = getClass().getDeclaredField(category + "List");
List result = field.get();
But generally you should avoid reflection. And if your objects are fixed - i.e. they don't change, simply use an if-clause.
The logically simplest way taking your question as given would just be:
StringBuffer which;
if (category.equals("game"))
which=gameList;
else if (category.equals("apps"))
which=appList;
else if (category.equals("movie"))
which=movieList;
else
... some kind of error handling ...
which.delete();
As Jon Skeet noted, if the list is big or dynamic you probably want to use a map rather than an if/else/if.
That said, I'd encourage you to use integer constant or an enum rather than a String. Like:
enum ListType {GAME, APP, MOVIE};
void deleteList(ListType category)
{
if (category==GAME)
... etc ...
In this simple example, if this is all you'd ever do with it, it wouldn't matter much. But I'm working on a system now that uses String tokens for this sort of thing all over the place, and it creates a lot of problems.
Suppose you call the function and by mistake you pass in "app" instead of "apps", or "Game" instead of "game". Or maybe you're thinking you added handling for "song" yesterday but in fact you went to lunch instead. This will successfully compile, and you won't have any clue that there's a problem until run-time. If the program does not throw an error on an invalid value but instead takes some default action, you could have a bug that's difficult to track down. But with an enum, if you mis-spell the name or try to use one that isn't defined, the compiler will immediately alert you to the error.
Suppose that some functions take special action for some of these options but not others. Like you find yourself writing
if (category.equals("app"))
getSpaceRequirements();
and that sort of thing. Then someone reading the program sees a reference to "app" here, a reference to "game" 20 lines later, etc. It could be difficult to determine what all the possible values are. Any given function might not explicitly reference them all. But with an enum, they're all neatly in one place.
You could use a switch statement
StringBuffer buffer = null;
switch (category) {
case "game": buffer = gameList;
case "apps": buffer = appsList;
case "movie": buffer = movieList;
default: return;
}