Is it a good idea to use reflections in a Web application? - java

I have developed below code with the intention to remove if else conditions so that code cyclomatic complexity should be less.
For this I have used reflection api and wrote method which takes condition as an argument and called respective method on the condition name basis.
This works fine, I want to know is it a good idea to use reflection (This code) in web application, so that I am free from checking conditions.
For example in below code we have different method with prefix state ex: stateSUBMIT, stateWithdraw etc.
we can call stateSUBMIT method by passing only "SUBMIT".
public class Participate {
public String execute(String methodName) {
String st = null;
try {
Method method = this.getClass().getDeclaredMethod(
"state" + methodName);
method.invoke(this);
} catch (Exception e) {
e.printStackTrace();
}
return st;
}
public void stateSUBMIT() {
System.out.println("in SUBMIT");
}
public void stateWithdraw() {
System.out.println("in Withdraw");
}
public void state() {
System.out.println("in state ");
}
public void statenull() {
System.out.println("in null ");
}
public static void main(String[] args) {
Participate p = new Participate();
p.execute("SUBMIT");
}
}

This is valid code, but can be achieved without reflections.
Step One: Define an interface
public interface Command {
public void execute();
}
Step Two: Create Concrete Implementations
public class StateCommand implements Command {
public void execute() {
// Your code.
}
}
Step Three: Add a collection of these to your original class
private Map<String, Command> commands;
Step Four: Populate
public MyClass() {
commands = new HashMap<String, Command>();
commands.put("state", new StateCommand());
}
Get that class and execute
public String callMethod(String name) {
Command command = commands.get(name);
if(command != null) {
command.execute();
}
}
This is just a relatively simple alternative to using reflections, which should be considered as a last resort.

I would avoid it. There are better alternatives. You could pick one of all the numerous web frameworks or you could code something similar without reflection. For example, use a HashMap from the action (SUBMIT, ...) to an object that implements an interface. That way you can call a method with parameters without reflection, which is slow and which provides no compile-time validations. This is not a recommendation (go with a framework!), but it is a better way of doing what you are doing right now.

Your implementation is beneficial in case if you are doing for making this Generic approach for all other other classes in your project.Its good if you are having re usability of this in many other scenarios.
But if its only for specific implementation which is not generalized then there are many simple ways to do this job, because if you will use java reflections than there is some amount of time complexity involved which is comparatively less if you do it without using reflectns.

Related

Java Passing in Type as Function Parameter

I come from a Python background and in Python you can pass in the type of an object as a parameter. But in Java you cannot do this, any tips on how to get something like this working?
private void function(Type TypeGoesHere)
Stock s = new TypeGoesHere();
s.analyze();
}
Java does not support Python’s way of referencing functions and classes. To achieve this behaviour, you have to use two advanced techniques: generics and reflection. Explaining these concepts is beyond the scope of a SO answer. You should read a Java guide to learn about them.
Yet here is an example how this would look like, assuming that the given class has a no-argument constructor:
public <T extends Stock> void analyzeNewStock(Class<T> clazz) throws Exception {
Stock s = clazz.newInstance();
s.analyze();
}
Then call this function with analyzeNewStock(MyStock.class).
As this is a rather complicated and error-prone approach, you’d rather define an interface that creates Stock instances:
public interface StockProvider {
Stock createStock(String value);
}
public class MyStockProvider implements StockProvider {
private final String valueTwo;
public MyStockProvider(String valueTwo) {
this.valueTwo = valueTwo;
}
#Override
public Stock createStock(String valueOne) {
return new MyStock(valueOne, valueTwo);
}
}
public class MyOtherClass {
public void analyzeNewStock(StockProvider provider) {
provider.createStock("Hi!").analyze();
}
public static void main(String[] args) {
analyzeNewStock(new MyStockProvider("Hey!"));
}
}
In Java you can pass a Class. You can do it like this:
private void function(Class c)
This is not very common procatice though. You can probably get wha you need by looking into Strategy pattern, or proper use of Object Oriented Programming (polymorphism).
If you are looking for a way to build some objects, look into Factory pattern.
If you want to create a generic class- look into this detailed answer: https://stackoverflow.com/a/1090488/1611957
You could use generics. For example:
private <T> void function(Class<T> clazz) {
try{
T t = clazz.newInstance();
//more code here
}catch(InstantiationException | IllegalAccessException ex){
ex.printStackTrace();
}
}
The Class<T> clazz shows what type to instantiate. The try/catch is just to prevent errors from stopping your code. The same idea is expanded in this SO post. More info here.
However, I'm not really sure why you would want to do this. There should easily be a workaround using a simple interface. Since you already know that you want an object with type Stock, you could pass an implementation of the interface. For example:
//interface to implement
public interface Stock {
public void analyze();
}
//rewrite of function
private void function(Stock s){
s.analyze();
}
And using two ways to call function:
//first way
public class XYZ implements Stock{
public void analyze(){
//some code here
}
}
//calling the function
function(new XYZ());
//second way
function(new Stock(){
public void analyze(){
//your code here
}
});

How to make this code DRYer

So I have a generated class (PartnerConnection) that provides DML operations to the SalesForce cloud platform. We were having issues where our long running integration process was failing due to connection issues with either SalesForce or the system running the code.
In order to solve this issue, I extended the PartnerConnection class with what I name an AdvancedPartnerConnection. The AdvancedPartnerConnection just overrides the methods of the PartnerConnection and wraps them with try/catch/retry logic.
#Override
public QueryResult query(String queryString) throws ConnectionException{
int attempt = 0;
ConnectionException lastException = null;
while(true){
if(attempt < maxAttempts){ //maxAttempts constant
if(lastException != null){
try {
//exponentially increase wait times
Long sleepTime =(long) Math.pow(sleepBase, attempt) * 300;
Thread.sleep(sleepTime);
} catch (InterruptedException e1) {
// something bad has happen, throw the connection exception
throw lastException;
}
}
attempt ++;
try{
//call super class method
return super.query(queryString);
}catch(ConnectionException e){
lastException = e;
}
}else{
throw lastException;
}
}
}
I've implemented this for a handful of the super class methods and the only difference is the method being called and its' parameters. It has become a real pain if I decided to change any of the retry logic as I want it to be consistent across all methods.
Does anyone have a way I could extract the retry logic into a separate class or method and maybe pass in the function call? I've done stuff like this in .NET but I'm not sure how to do it in java.
You basically want to capture all calls to all object methods and apply some logic to all of them.
You could create a Proxy and retry in the handler invoke method.
With this approach based on the method signature you decide what to do.
Another approaches could use AspectJ or any other AOP framework, but your use case is very simple to add that kind of dependencies, IMO.
If the class which you want to add some behaviour is not yours then this solution might not be the most elegant. But if you are willing to sacrifice some elegance to gain maintainability (since you are not replicating code) then you could:
class NotYourClass {
public void voidMethod() {}
public int intMethod(int n) { return 0; }
}
To create a proxy you must create an interface with all the methods of the class. This is the crappy part, but this do not add any dependency to your application.
interface YourInterface {
public void voidMethod();
public int intMethod(int n);
}
Next thing you need is an InvocationHandler that will contain the behavior.
class YourInvocationHandler implements InvocationHandler {
private final NotYourClass target;
public YourInvocationHandler(NotYourClass target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
// Here you must look to the methods that are the ones that you want.
return method..invoke(target, args);
} catch (Exception e) {
// Retry?
method.invoke(target, args);
}
}
}
Please bear in mind that this is from the top of my head. But should be something along those lines.
If creating that interface is something unnacceptable for you then you can look at some AOP frameworks.

How to protect method signature in java called from other language (javascript)

I have a question about combining java with javascript. In our application we have gui build in javascript and server side build in java. In javascript we write that we want to call methodX from classY in java. The problem is that java doesen't know anything about javascript so when we change something in java we could break javascript code. Even plain refactor option in eclipse can break our javascript without knowing (changing method name, removing params, renaming setter and getter in DTO object). The question is how to counteract against it. I was thinking about writing some annotations in java so after changing method signature you will get compilation error (is it even possible to write this kind of annotation) but I don't want to reinvent the wheel again if there is some kind of tool which will do it for me. I would be grateful for any help.
The question is how to counteract against it.
Probably the most practical solution is to develop a set of automated tests (e.g. unit or system tests) that are specifically designed to "exercise" all of the cases where there is a Java API that is called from Javascript (or vice-versa)
I think there are a couple of solutions(workarounds) for your problem.
1)Mapping certain strings with methods.
public class JavascriptCallable {
private static final String jsIdentifierMethod1 = "method1";
private static final String jsIdentifierMethod2 = "method2";
/**
* All requests from JS should be redirected to this method.
*
* #param methodName Name of the method
*/
public void requestFromJavascript (String methodName) throws Exception {
if (methodName.equals(jsIdentifierMethod1)){
method1();
} else if (methodName.equals(jsIdentifierMethod2)){
method2();
} else{
throw new Exception("Method not supported");
}
}
public void method1(){
// Do something
}
public void method2() {
// Do something
}
}
2)Having separate methods eligible for js calling. This will help if you are using reflections to call the methods
public class JavascriptCallable {
/*----------------Methods to be called by js. Never refractor------------------*/
public void noRefractorMethod1() {
method1();
}
public void noRefractorMethod2() {
method2();
}
/*-------------------------------------------------------------------------------*/
/*---------Methods with business logic. Refractoring these will not mess your js-----------*/
public void method1() {
// Business logic
}
public void method2() {
// Business logic
}
/*-------------------------------------------------------------------------------*/
}
Please let me know if this helps.

Detecting whether a method/function exists in Java

Is there a method/function in Java that checks if another method/function is available just like function_exists(functionName) in PHP?
Here I am referring to a method/function of static class.
You can find out if a method exists in Java using reflection.
Get the Class object of the class you're interested in and call getMethod() with the method name and parameter types on it.
If the method doesn't exist, it will throw a NoSuchMethodException.
Also, please note that "functions" are called methods in Java.
Last but not least: keep in mind that if you think you need this, then chances are that you've got a design problem at hand. Reflection (which is what the methods to inspect the actual Java classes is called) is a rather specialized feature of Java and should not generally be used in business code (although it's used quite heavily and to some nice effects in some common libraries).
I suspect you're looking for Class.getDeclaredMethods and Class.getMethods which will give you the methods of a class. You can then test whether the one you're looking for exists or not, and what it's parameters are etc.
You can use Reflections to lookup if the method exists:
public class Test {
public static void main(String[] args) throws NoSuchMethodException {
Class clazz = Test.class;
for (Method method : clazz.getDeclaredMethods()) {
if (method.getName().equals("fooBar")) {
System.out.println("Method fooBar exists.");
}
}
if (clazz.getDeclaredMethod("fooBar", null) != null) {
System.out.println("Method fooBar exists.");
}
}
private static void fooBar() {
}
}
But Reflection is not really fast so be careful when to use it (probably cache it).
Try using the Class.getMethod() method of the Class class =)
public class Foo {
public static String foo(Integer x) {
// ...
}
public static void main(String args[]) throws Exception {
Method fooMethod = Foo.class.getMethod("foo", Integer.class);
System.out.println(fooMethod);
}
}
Here my solution using reflection...
public static boolean methodExists(Class clazz, String methodName) {
boolean result = false;
for (Method method : clazz.getDeclaredMethods()) {
if (method.getName().equals(methodName)) {
result = true;
break;
}
}
return result;
}
You can use the reflection API to achieve this.
YourStaticClass.getClass().getMethods();
You can do this like this
Obj.getClass().getDeclaredMethod(MethodName, parameterTypes)

Modulation of adding new Strings -> Method calls

If I have a program that does the following:
if(input=='abc'){do x}
if(input=='def'){do y}
In the future, I may want to add another piece of code like so:
if(input=='ghy'){do x}
As you can see, I am adding a new 'if' statement for a different conditional BUT using the SAME function X.
The code in future has potential to have lots of different IF statements (or switches) all of which are comparing a string vs a string and then performing a function. Considering the future expansion, I was wondering if there is a possible 'neater', 'modular' way of achieving the same results.
It's a shame I can't combine the String with a Method call in a hashtable (String, method) in Java. That way I could just store any new procedures inside a hashtable and grab the relevant method for that String.
Any ideas?
Thank you
EDIT: Thank you for everyone's solutions. I was surprised by the quantity and quality of replies I received in such a small amount of time.
Maybe you can use enum. Example:
public enum InputType
{
abc, def
{
#Override
public void x()
{
System.out.println("Another method");
}
},
ghy;
public void x()
{
System.out.println("One method");
}
}
And further:
InputType.valueOf("abc").x();
Cheers!
I guess you could always use a Map<String, Runnable> and map to anonymous Runnable implementations:
myMap.put("abc", new Runnable() { public void run() { do x } });
...
myMap.get(input).run();
You should take a look at the command pattern. There are several ways of implementing it, and frameworks such as Spring can help you do with in a clean way.
But in a simple manner here's what you could do:
1-Create a Command interface with a method that your program will have to call to do the task, say doTask()
2-Create classes for command X and Y, implementing the Command interface.
3-Create a Map<String, Command> that will map your commands (X and Y) to logical names
4-Create a configuration file of your choice, say a .properties file that will map your input to your command names: abc=X, def=Y, ghi=X
5-Your program then does lookups on the config file to know which command to run according to the input.
A lot of ifs always tell us that we could do this better. In your case better option is to use design pattern e.g. Chain of responsibility. You will have good implementation which you can dynamic change and your code will be easier to maintenance than ifs implementation.
Take a look at this adaptation chain of responsibility to your case:
Main:
public static void main(String[] args) {
ClassA classA = new ClassA(Arrays.asList("abc", "ghi"));
ClassB classB = new ClassB(Arrays.asList("def"));
classA.setNextInChain(classB); // you can always write Builder to do this
String input = "def";
classA.execute(input);
}
BaseClass:
public abstract class BaseClass {
private Collection<String> patterns = Collections.EMPTY_LIST;
protected BaseClass nextInChain;
protected abstract void doMethod(); // your doA, doB methods
public void execute(String input) {
// this replace many ifs in your previous implementation
if (patterns.contains(input)) {
doMethod();
} else {
nextInChain.execute(input);
}
}
public void setPatterns(Collection<String> patterns) {
this.patterns = patterns;
}
public void setNextInChain(BaseClass nextInChain) {
this.nextInChain = nextInChain;
}
}
Class in chain:
public class ClassA extends BaseClass {
ClassA(Collection<String> patterns) {
setPatterns(patterns);
}
#Override
protected void doMethod() {
// do A
}
}
public class ClassB extends BaseClass {...}

Categories

Resources