I'm starting to do a bit of advanced things in Java (For me are advanced xD).
I had this:
interface ResultSet {
public void close();
}
class DbResult {
ResultSet data;
Statement statement;
public void close() {
this.data.close();
this.statement.close();
}
}
I've tried to do this:
interface ResultSet { //I think that is abstract or something
public void close();
}
abstract class DbResult implements ResultSet {
Statement statement;
#Override
public void close() {
super.close();
this.statement.close();
}
}
Obviously it don't works because ResultSet is not a superclass. I also tried to make DbResult an interface and extending ResultSet but it tells me that interface methods cannot have a body, so I don't know how to do this.
I'm trying to do this so I can close the result statement and result having only one variable instead of 2, so is less prone to memory leaks for forgetting closing the statement.
The Database class queries the database this way:
class Database {
private Connection connection;
/* Here a constructor that
inits the connection and such things */
public DbResult query(String q) {
Statement statement = this.connection.createStatement();
DbResult result = (DbResult)statement.executeQuery(q);
result.statement = statement;
return result;
}
EDIT:
Ok, now that I know that I can't I want to know if I can do this in a hackish form I though:
Is there a way of checking if a method that does not exists is called in a class, catch it and invoke that method name in another variable?
For example, ResultSet has a method called getString(). I want to know if is possible to call DbResult.getString("blah"); and DbResult will redirect that method to this.data but withou implementing the getString method inside the DbResult class.
I would like to know if is possible because there are tons of functions in the ResultSet and calling DbResult.data.METHOD is less elegant than DbResult.METHOD.
Is there a way of checking if a method that does not exists is called
in a class, catch it and invoke that method name in another variable?
So you want to wrap calls to an instance without having to extend it or implementing each of its methods, that's actually possible, but only for methods exposed over interfaces.
Good news is that ResultSet is in fact an interface.
This can be done by means of dynamic proxies (see Proxy and InvocationHandler).
You can create a Proxy backed by an InvocationHandler which wraps the ResultSet. Any calls to your proxy instance will be delegated to the InvocationHandler, which can process them directly or, in your case, delegate them to the wrapped actual ResultSet instance.
public class MyResultSetInvocationHandler implements InvocationHandler {
private final ResultSet wrappedResultSet;
private MyResultSetInvocationHandler(ResultSet resultSet) {
wrappedResultSet = resultSet;
}
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
// call method on delegate
Object result = method.invoke(wrappedResultSet, args);
// optionally do something with the result, and return it afterwards
return result;
}
catch (Throwable ex) {
// handle exception, or rethrow it
throw ex;
}
}
/**
* Factory method, creates a dynamic proxy wrapping the given result set.
*/
public static ResultSet wrap(ResultSet delegate) {
MyResultSetInvocationHandler handler = new MyResultSetInvocationHandler(delegate);
return (ResultSet) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { ResultSet.class }, handler);
}
}
Usage:
// the actual result set
ResultSet resultSet = ...
// and your wrapped proxy/handler as a surrogate
resultSet = MyResultSetInvocationHandler.wrap(resultSet);
Perhaps what you want to use is an abstract class and not an interface, something like:
interface A2 {
void foo();
void otherAbstractMethod();
}
abstract class AbstractA2 implements A2 {
#Override // implemented metthod
public void foo() {
System.out.println("From the default method");
}
#Override //unimplemented abstract method
public abstract void otherAbstractMethod();
}
class B2 extends AbstractA2 {
#Override
public void foo() {
super.foo();
System.out.println("From the override");
}
#Override
public void otherAbstractMethod() {
// TODO add some code
// the line below won't compile
// super.otherAbstractMethod();
}
}
and to test it
public class TestA {
public static void main(String[] args) {
A2 myA = new B2();
myA.foo();
}
}
Edit
Regarding the changes in your question, which changes everything and drastically, I'm confused (again). Is ResultSet your interface, or are you trying to implement the java.sql.ResultSet? If the latter, your code will be fraught with difficulty since your class cannot extend and cannot substitute for the actual type of ResultSet returned by the query. I don't see any substitute for your using composition and not inheritance. In other words, go with what you were originally doing -- creating classes that contain ResultSet fields but not one that implements the interface.
Note that you can implement ResultSet if you use the Decorator Pattern. With this you would create your own class that is a "wrapper" for the original type, and it will require you to use composition and inheritance, and to create all the needed methods for the interface and then delegate them to the ResultSet component.
For example, ResultSet has a method called getString(). I want to know if is possible to call DbResult.getString("blah"); and DbResult will redirect that method to this.data but withou implementing the getString method inside the DbResult class.
No, you would have to have all these methods implemented in your child decorator class.
Guess what: it's already part of Java (since version 7):
Java API Documentation: java.lang.AutoCloseable
public interface AutoCloseable {
void close();
}
ResultSet, Statement (and many other classes) already implement this interface.
And the best thing: resources managed by the try in a try-statement are automatically closed, if they implement this interface.
Related
I am looking for a Java equivalent for python's with statement, and I read about implementing the AutoCloseable interface and using try with resources.
In python, the context manager (with statement) uses two methods: __enter__ and __exit__, but in Java, the try with resources block uses only close, which is the equivalent of __exit__.
Is there an equivalent for the __enter__ method, in order to perform a certain method automatically when entering the try with resources block, and not only when the block is over?
The equivalent is basically whatever you are calling in the try to get an instance of your AutoCloseable. This could be a constructor like:
try (MyClass obj = new MyClass()) { …
Where the class having such a constructor looks like:
public class MyClass implements AutoCloseable {
public MyClass() {
// do "enter" things...
}
#Override
public void close() {
// close resources
}
}
Depending on what you need "enter" to do, you might instead prefer a static producer for your class, which would look like this:
try (MyClass obj = MyClass.getInstance(someProperties)) { …
Then your class might look something like this:
public class MyClass implements AutoCloseable {
private MyClass() {
// instantiate members
}
public static MyClass getInstance(Properties config) {
// you could implement a singleton pattern or something instead, for example
MyClass obj = new MyClass();
// read properties...
// do "enter" things...
return obj;
}
#Override
public void close() {
// close resources
}
}
You could even call a factory or builder pattern in the try to produce your AutoCloseable. It all depends on your design and what you need the instance to do on "enter".
I have several methods in a class that require a boolean to be set to true in order to execute correctly.
I could write the if statement in each method, but it is not convenient if I or someone else wants to ad another method. I or he could forget about the check.
Is there a way in java to execute a method before each other methods (exactly like JUnit does with #BeforeEach ) in a class ?
Edit: Lots of very interesting techniques/answers/concepts proposed. I'll be in touch when I've understood them. Thanks.
Lets make a method turnBooleanTrue() where effectively the boolean is set to true in order for the method to be execute correctly.
Then, you can write up your very own InvocationHandler that would intercept calls to your objects, and then reflectively (using reflection API) invoke first the turnBooleanTrue() method followed by the method to which the call was made.
Will look something like this
public class MyClassInvocationHandler implements InvocationHandler {
// initiate an instance of the class
MyClass myClass = new MyClassImpl();
#Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// look up turnBooleanTrue() method
Method turnBooleanTrue = myClass.getClass().getMethod("turnBooleanTrue");
// invoke the method
turnBooleanTrue.invoke(...); // toggle the boolean
// invoke the method to which the call was made
// pass in instance of class
Object returnObj = method.invoke(myClass, args);
return returnObj;
}
EDIT
Added some lines to have an object of MyClass initialized. You need something to invoke the method on and maintain the state. Changed util to myClass in the code example above.
Considering my use case, it was a bit overkill to use AOP or other concepts. So I basically did a check in each functions.
With AOP, this is how what you need would look:
// wraps around all methods in your class that have a boolean parameter
#Around(value = "#target(*..YourClass) && args(yourBool)", argNames = "jp,yourBool")
Object scheduleRequest(ProceedingJoinPoint jp, boolean yourBool) {
if (yourBool) {
jp.proceed(yourBool);
} else {
throw new RuntimeException("cannot execute this method!");
}
}
This would handle the case that the method take the boolean you say needs evaluation as its (only) parameter. If it comes from a different source, you may need to wire it into the aspect somehow, that depends on your overall design.
I suggest a simple solution by dividing your workflow in four components.
You have an interface you use to execute commands.
You have an interface that defines which commands you can use.
You have one wrapper that analyzes your boolean value.
You have an implementation of the work performing class, that implements the second interface.
Your wrapper initialize the worker.
Your wrapper exposes an action performing command that accepts the executing interface.
if the boolean is true, pass the worker to the executing interface work method.
the executing interfaces work method calls the work function on the command instance interface, the worker.
See it online: https://ideone.com/H6lQO8
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
WorkDistributer wd = new WorkDistributer();
wd.enable();
wd.performAction((w) -> {w.printHello();});
wd.disable();
wd.performAction((w) -> {w.printHello();});
wd.enable();
wd.performAction((w) -> {w.printAnswer();});
wd.disable();
wd.performAction((w) -> {w.printAnswer();});
}
}
class WorkDistributer
{
private boolean enabled = false;
private ActionPerformer worker;
public WorkDistributer() {
this.worker = new Worker();
}
public void enable() {
enabled = true;
}
public void disable() {
enabled = false;
}
public void performAction(ActionCommand command) {
if(this.enabled) {
command.run(this.worker);
}
}
}
class Worker implements ActionPerformer {
public void printHello() {
System.out.println("hello");
}
public void printAnswer() {
System.out.println(21 * 2);
}
}
interface ActionPerformer {
public void printHello();
public void printAnswer();
}
interface ActionCommand {
public void run(ActionPerformer worker);
}
Is there a way to always execute a function before any other function of a class is called?
I have a class where I need to refresh some fields always before any function is called:
public class Example {
private int data;
public void function1(){
}
public void function2(){
}
//#BeforeOtherFunction
private void refresh(){
// refresh data
}
}
Because it seems to be bad programming, I don't want to call refresh at the beginning of every other function. Since other persons are going to work on this project as well, there would be the danger, that somebody extends the calls and doesn't call refresh.
JUnit has a solution for this with the #Before-Annotation. Is there a way to do this in other classes as well?
And by the way: If you know a programming pattern wich solves this problem in another way than executing a function everytime any function is called, that would be very helpful, too!
Use a dynamic proxy in which you can filter to those methods before which your specific "before" method should be called. And call it in those cases before dispatching the call. Please see the answer from How do I intercept a method invocation with standard java features (no AspectJ etc)?
UPDATE:
An interface is needed to be separated for the proxy. The refresh() method cannot remain private. It must be public and part of the interface (which is not nice here) to be able to be called from the proxy.
package CallBefore;
public interface ExampleInterface {
void function1();
void function2();
void otherFunction();
void refresh();
}
Your class implements that interface:
package CallBefore;
public class Example implements ExampleInterface {
#Override
public void function1() {
System.out.println("function1() has been called");
}
#Override
public void function2() {
System.out.println("function2() has been called");
}
#Override
public void otherFunction() {
System.out.println("otherFunction() has been called");
}
#Override
public void refresh() {
System.out.println("refresh() has been called");
}
}
The proxy which does the trick. It filters the needed methods and calls refresh().
package CallBefore;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ExampleProxy implements InvocationHandler {
private ExampleInterface obj;
public static ExampleInterface newInstance(ExampleInterface obj) {
return (ExampleInterface) java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), new ExampleProxy(obj));
}
private ExampleProxy(ExampleInterface obj) {
this.obj = obj;
}
#Override
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Object result;
try {
if (m.getName().startsWith("function")) {
obj.refresh();
}
result = m.invoke(obj, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
}
return result;
}
}
The usage:
package CallBefore;
public class Main {
public static void main(String[] args) {
ExampleInterface proxy = ExampleProxy.newInstance(new Example());
proxy.function1();
proxy.function2();
proxy.otherFunction();
proxy.refresh();
}
}
Output:
refresh() has been called
function1() has been called
refresh() has been called
function2() has been called
otherFunction() has been called
refresh() has been called
This may not solve your exact problem but at least could be a starting point if you are allowed considering a re-design. Below is a simple implementation but with some small touches I believe you can achieve a more elegant solution. BTW, this is called Dynamic Proxy Pattern.
First thing you need is an interface for your class.
public interface Interface {
void hello(String name);
void bye(String name);
}
public class Implementation implements Interface {
#Override
public void hello(String name) {
System.out.println("Hello " + name);
}
#Override
public void bye(String name) {
System.out.println("Bye " + name);
}
}
Then java.lang.reflect.Proxy class comes to help. This class is able to create an instance for a given interface at runtime. It also accepts an InvocationHandler which helps you to capture method calls and looks like this.
public class InvocationHandlerImpl implements InvocationHandler {
private final Object instance;
public InvocationHandlerImpl(Object instance) {
this.instance = instance;
}
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result;
try {
System.out.println("Before");
result = method.invoke(instance, args);
System.out.println("After");
} catch (Exception e){
e.printStackTrace();
throw e;
} finally {
System.out.println("finally");
}
return result;
}
}
After all your client code will look like this.
Interface instance = new Implementation();
Interface proxy = (Interface)Proxy.newProxyInstance(
Interface.class.getClassLoader(),
new Class[] { Interface.class },
new InvocationHandlerImpl(instance));
proxy.hello("Mehmet");
proxy.bye("Mehmet");
Output for this code is
Before
Hello Mehmet
After
finally
Before
Bye Mehmet
After
finally
I would define getters for every field and do the refreshment inside the getter. If you want to avoid unrefreshed access to your private fields at all, put them in a superclass (together with the getters which call refresh).
Depending on your project structure, it may be also sensible to introduce a separate class for all data that is regularly refreshed. It can offer getters and avoid that anyone accesses the non-refreshed fields.
Not in Java SE, but if you are using Java EE, you could use interceptors.
For standalone applications, you could consider using a bytecode manipulation framework, like javassist.
You can have a protected getter method for data. Access getData method instead of using data field. Child classes will see only getData and will have updated data every time.
public class Example {
private int data;
public void function1(){
}
public void function2(){
}
protected int getData(){
refresh();
return data;
}
//#BeforeOtherFunction
private void refresh(){
// refresh data
}
}
It is better to write another method which will be made protected(accessible to the child classes) which will call first the refresh method and then call the function.
This way the data would be refreshed before the function is called everytime(As per your requirement).
eg:
protected void callFunction1(){
refresh();
function();
}
Thanks,
Rajesh
You should use Decorator in this case. Decorator is a good choice for something like interceptor. Example here: https://msdn.microsoft.com/en-us/library/dn178467(v=pandp.30).aspx
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.
I've the following class. It has the code to connect to SAP in its constructor. There is an abstract method(the subclasses define the implementation) which I want to mock.
public abstract class BapiExecutor {
...
public BapiExecutor(final SapConnectionInfo connectionInfo)
throws java.lang.Exception {
if (!validConnectorData()) {
throw new IllegalArgumentException(
"Does not have valid data to connect to SAP");
}
initializeState(connectionInfo);
}
public abstract Object execute() throws Exception ;
....
}
The unit I want to test is :
I want to mock the call to execute() method.
private String invokeBapiToAddAssociation(Map associationMap,
SapConnectionInfo connectionInfo) {
EidCcBapiExecutor executor = null;
String bapiExecutionResult = null;
try {
executor = new EidCcBapiExecutor(connectionInfo, associationMap);
bapiExecutionResult = (String) executor.execute();
} catch (Exception e) {
e.printStackTrace();
throw new CcGenericException(
"Exception occurred while invoking the EID-CC Association BAPI executor!",
e);
}
return bapiExecutionResult;
}
Any frameworks in Java that supports the mocking of parametrized constructors?
i just want to avoid connecting to SAP in the constructor.
JMock with the ClassImposteriser can do that, as can most good mocking frameworks.
The ClassImposteriser creates mock
instances without calling the
constructor of the mocked class. So
classes with constructors that have
arguments or call overideable methods
of the object can be safely mocked.
You can simply create the mock class, subclassing the abstract BapiExecutor class, and implementing the behavior you want in execute() (or any other method). You don't need to revert to a framework here.
Could you please elaborate about what the blocking point is ?
I expect that the EidCcBapiExecutor extends from BapiExecutor.
public class EidCcBapiExecutor extends BapiExecutor {
...
}
Than you could create the Mockup class for testing a specific method like:
public class EidCcBapiExecutorMockup extends EidCcBapiExecutor{
public EidCcBapiExecutorMockup (final SapConnectionInfo connectionInfo){
super(connectionInfo);
}
public Object execute() throws Exception {
// You mockup code
}
}
If you want to test the constructor you can create the class like:
public class EidCcBapiExecutorMockup extends EidCcBapiExecutor{
public EidCcBapiExecutorMockup (){
super(new SapConnectionInfo());
}
}
The object you place in the Constructor could be created in the setUp method of you JUnit test!