java - How to select the best .class file from a folder? -
i have 1 application handling math operator . app has interface operator so:
public interface operator { double calculate(double firstnumber,double secondnumber); string getsign(); }
i have 4 class implement operator so:
public class plus implements operator { public double calculate(double firstnumber,double secondnumber) { return firstnumber + secondnumber; } public string getoperator() { return "+"; } } public class minus implements operator { public double calculate(double firstnumber,double secondnumber) { return firstnumber - secondnumber; } public string getoperator() { return "-"; } }
and on...
i compiling classes , put .class file in folder("myfolder") . in main program(main app folder) type of operator user , according operator want choose .class file correct 1 don't know how . can me ?
don't. why? using reflection cost down performance.
suggest:
final string op_plus = "+"; final string op_minus = "-"; list<operator> listoperator = new list<>(){ new plus(), new minus() }; operator getoperator(string inputoperator) throws notsupportedexception { for(operator op : listoperator) if(op.getoperator().equals(inputoperator)) return op; throw new notsupportedexception(); }
using:
operator op = getoperator(op_plus); double result = op.calculate(d1, d2);
in case of have way (teacher tell you, etc....), can use java relection.
read java reflection first or thread http://tutorials.jenkov.com/java-reflection/methods.html
following answer you:
string requiredoperator =... // input file file = new file("c:\\myclasses\\"); url url = file.tourl(); // file:/c:/myclasses/ url[] urls = new url[]{url}; // create new class loader directory classloader cl = new urlclassloader(urls); // load in class; myclass.class should located in // directory file:/c:/myclasses/com/mycompany // class cls = cl.loadclass("com.mycompany.myclass"); <= how load class class[] classes; // load classes: plus.class, minus.class array classes = new class[]{ cl.loadclass("com.mycompany.plus"), cl.loadclass("com.mycompany.minus") }; method method; object instance; string identifier; for(class cls : classes) { instance = cls.newinstance(); method = cls.getmethod("getoperator", null); // method getoperator of operator interface not have parameter identifier = (string)method.invoke(instance, null); if(identifier.equals(requiredoperator)) { method = cls.getmethod("calculate", new class[] { double.class, double.class } ); // 2 params double return (double)method.invoke(instance, double1, double2); } }
i did not test code that's way you
Comments
Post a Comment