Here is an example of my code:
class foo extends afoo{
#HTTPPost
returnClass runTransaction(RequestData req){
return sendData(req, returnClass.class)
}
#HTTPGet
returnClass runTransaction2(RequestData req){
return sendData(req, returnClass.class)
}
}
abstract class afoo {
public <T> T sendData(ARestMessage req, Class<T> returnClassType)
//here i need the annotation of the calling method
}
Basically i'm building a pretty complex messaging system and I want to put as much of the switching and configuration in annotations as i can.
Yes, I know there are a few libraries out there (like Google reflection) that would make this easier but in order for me to use them I have to do 4-6 months of paperwork and meetings with Enterprise Architecture to get approval to use them. Seeing the project must be finished in 2 months, i'm doing it by hand.
So what i'm doing is creating annotations that developers can annotate the methods with indicating the way the resulting service is expecting the data to be sent. That could be a get, post, put, etc. Inside the abstract class, that all service classes extend, is a senddata method. That method must be able to figure out which method was used to call it, aka, was it by runTransaction or runTransaction2, so sendData pull that methods annotations and therefore know exactly how to send the data to the service.
now I found this (which is the first line of code in my sendData method)
final Method callingMethod = this.getClass().getEnclosingMethod();
But it keeps returning null. i've read the javadoc on it several times and i'm not understanding why it keeps returning null.
I understand that I can get the parent caller using the stack, but I would prefer not to do that because this application shares app server memory with another application that does a TON of AOP work. That AOP work is really good at messing up stacks in unintended ways, so I would rather solve this using straight reflection.
Does anyone know why this method keeps returning null? Is it because its contained in an abstract class and not my foo class itself? Is there a way to accomplish this using the techniques I would prefer to use?
thanks
The method Class.getEnclosingMethod() does not do what you think it does. Here is the Javadoc for it:
If this Class object represents a local or anonymous class within a
method, returns a Method object representing the immediately enclosing
method of the underlying class. Returns null otherwise. In particular,
this method returns null if the underlying class is a local or
anonymous class immediately enclosed by a type declaration, instance
initializer or static initializer.
Specifically, it returns the outer, enclosing method for an anonymous inner class, that was defined in the context of that method. I did not see anywhere in your description that these messaging methods are being called from anonymous/local inner classes. Here is an example in code (jUnit required):
import java.lang.reflect.Method;
import org.junit.Assert;
import org.junit.Test;
interface Introspector {
public Method getEnclosingMethod();
}
public class Encloser {
public Encloser() {
super();
}
public Method noop() {
final Introspector inner = new Introspector() {
#Override
public Method getEnclosingMethod() {
return getClass().getEnclosingMethod();
}
};
return inner.getEnclosingMethod();
}
#Test
public void testEnclosingMethods() throws Exception {
final Encloser encloser = new Encloser();
Method method = encloser.getClass().getEnclosingMethod();
Assert.assertNull(method);
method = encloser.noop();
Assert.assertNotNull(method);
}
}
Your current solution sounds pretty complicated. Are you planning on walking up the method call chain (which you can only do by dumping the stacktrace btw) and looking for annotations after doing some hefty reflection? I foresee alot of bugs. Frankly, employing some kind of builder pattern would probably be better for your scenario.
There's no point using annotation here, just pass another argument to method sendData().
Related
I am working on junit and using PowerMockRunner to mock static methods.
I am aware that static methods can be mocked using when(...).thenReturn(...)
I need to mock a certain method that takes four arguments:
public static void addInputPath(String, Boolean, Integer, Double)
I need the third parameter(Integer) in any call to this method to be replaced by, say 10. All other parameters should just be passed as is.
In other words, I need to do something like this:
when(addInputPath(str, bool, intgr, dbl)).thenReturn(addInputPath(str, bool, 10, dbl));
Is there a way to do this?
So, when I get your requirements right, what you actually want to do is to intercept the call to addInputPath() and invoke it with a different parameter?
If so: I am not sure if this can be done with any mocking framework (and I doubt that it is possible). Mocking frameworks are about mocking calls; not about instrumenting/intercepting calls.
Coming back to your problem, this is a nice example why static calls far too often cause problems. Thus, the best solution in my eyes would be to change your method xyz() to avoid that thing calling addInputPath() directly. Like this:
interface InputPathAdder {
void addInputPath(str, ... );
}
class ForwardingInputPathAdder implements InputPathAdder {
// implements the method by calling the static method
and all of a sudden, you can also do:
class ForwardingInputPathAdderWithFixedIntegerParm implements InputPathAdder {
// implements the method by calling the static method, but using 10 always
( obviously, naming could be improved here )
And now: you use dependency injection to give your "class under test" some Object implementing InputPathAdder. This could be either one that is completely mocked for testing; or it could be one that just does forwarding (in your production environment; or it could be the one that fixes the 3rd parameter). And no need for mocking for your "intercept" situation.
In class today, we were talking about reflection in Java programming. A part of the lesson today was about using InvocationHandlers in Java, rather than just implementing an interface.
When I asked the teacher what the advantages were of using an invocation handler, there wasn't a clear answer.
So let's say we have an interface Plugin
public interface Plugin {
void calculate(double a, double b);
String getCommand();
}
you can easily implement this interface in a class Multiply
public class Multiply implements Plugin {
#Override
public void calculate(double a, double b){
return a * b;
}
#Override
public String getCommand(){
return "*";
}
}
Then why would I prefer another implementation using an InvocationHandler?
public class MyMock {
public static Object createMock(Class myClass) {
InvocationHandler handler = new MyInvocationHandler();
Object result = Proxy.newProxyInstance(myClass.getClassLoader(), new Class[]{myClass}, handler);
return result;
}
}
Thanks in advance :)
Proxy is a dynamic proxy, allowing you to alter the behaviour of objects at runtime instead of having to decide it at compile-time.
For example, let's say we want to return only nulls during the night. If you were to implement it statically, you would need to write the logic into all the classes with something like
if(isNight())
return null;
return normalValue;
This requires that you can actually change the class, and you would need to change all the classes.
However with a Proxy, you can write the above logic into the InvocationHandler and the normal classes won't even know that their values aren't used during the night. Instead of the original class, your code is now using the dynamic proxy, but it won't know the difference.
This also allows you to have multiple InvocationHandlers, so you could run your code with parameters to decide if you want to log calls, prevent calls for security reasons, or any other such thing, which would be quite impossible to do with static implementations.
You're unlikely to use those classes directly though, as they're quite low level. However AOP uses either dynamic proxies or bytecode manipulation to achieve its task. If you've ever used Spring, you've most likely used an InvocationHandler without knowing it. When you put #Transactional on a method, an InvocationHandler is what will intercept the method call and start (and end) the transaction for you.
InvocationHandler together with Proxy allow implementation of an interface at runtime, without the faff of compiling interface-specfic code. It is often used to mediate access to an object of a class that implements the same interface. Proxy does not allow changing the behaviour of existing objects or classes.
For instance, it can be used in remote method calling on the client side, forwarding method call across a network to a server.
My first use of Proxy was for logging method calls to a wide interface that represented command received over a wire format. This easily produced very consistent debug output, but required little maintenance when the interface changed.
Java annotation interfaces may be represented by a Proxy proxy object at runtime, to prevent an explosion of classes.
java.beans.EventHandler was useful before lambdas and method references came along, to implement event listeners without bloating jars.
As per a more specific or real-world example, you may run into these kind of reflection usages more using a third-party or open-source API. A very popular example of this would be minecraft, specifically Bukkit/Spigot.
This api is used to write plugins, which the main server then loads and runs. This means you're not 100% in control of some of the code that exists in that codebase, inviting solutions using reflection. Specifically, when you want to intercept calls being made in the API (or even another plugin's API, e.g. Vault for those familiar), you may look to use a Proxy.
We'll stick with the minecraft example, but we're parting from bukkit's api here (and pretending it's not accepting PRs). Say there's a part of the API that just doesn't quite work the way you need.
public interface Player {
//This method handles all damage! Hooray!
public void damagePlayer(Player source, double damage);
}
This is great, but if we want to code something where we could find out if a player was damaged (maybe to make cool effects?), we'd need to modify the source (not possible for distributed plugins), or we'd need to find a way to figure out when #damagePlayer has been called and with what values. So in comes a Proxy:
public class PlayerProxy implements IvocationHandler {
private final Player src;
public PlayerProxy(Player src) {
this.src = src;
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
//Proceed to call the original Player object to adhere to the API
Object back = m.invoke(this.src, args);
if (m.getName().equals("damagePlayer") && args.length == 2) {
//Add our own effects!
//Alternatively, add a hook so you can register multiple things here, and avoid coding directly inside a Proxy
if (/* 50% random chance */) {
//double damage!
args[1] = (double) args[1] * 2;
//or perhaps use `source`/args[0] to add to a damage count?
}
}
}
}
With our Proxy, we've effectively created a fake Player class, one which will simply call the methods in place for Player. If our PlayerProxy is invoked with myPlayerProxy.someOtherMethod(...), then it will happily pass along a call to myPlayerProxy.src.someOtherMethod(...) via reflection (the m#invoke in the method above).
Simply put, you hot-potato the objects in the library to suit your needs:
//we'll use this to demonstrate "replacing" the player variables inside of the server
Map<String, Player> players = /* a reflected instance of the server's Player objects, mapped by name. Convenient! */;
players.replaceAll((name, player) ->
(PlayerProxy) Proxy.newProxyInstance(/* class loader */, new Class<?>[]{Player.class}, new PlayerProxy(player)));
InvocationHandler can handle multiple interfaces too. By using a generic Object to pass along the invocations, you can then listen to a variety of different methods in the API all within the same Proxy instance.
Is there a way to call a GreetingServiceImpl 's Method from other Java class in Server Side package. I want to extract a piece of data from a method in GreetingServiceImpl but I am unable to do so since it requires 'static' methods and GWT RPC methods are not static. I tried
GreetingServiceImpl obj=new GreetingServiceImpl();
String mSelect=obj.getModel(Manufacturer);
but the code is not working. It's not even executing
I also tried Googling but didn't find anything relevant that can do the thing easily.
Is there a simple way to do it?
You are doing it correctly. Debug and make sure your method isn't doing anything that requires a ServletContainer. For example, if your GreetingServiceImpl has init() and destroy() implementations, they won't get called since you are using it as a Java class instead of a HttpServlet. Also make sure your method doesn't need a HttpSession since you won't have one.
I also recommend you use an instance variable instead of calling new GreetingServiceImpl(); all the time:
private static GreetingServiceImpl instance = null;
public static GreetingServiceImpl getInstance() {
if (instance == null) {
instance = new GreetingServiceImpl();
}
return instance;
}
So from then on, from the server side, you'd call:
String mSelect=GreetingServiceImpl.getInstance().getModel(Manufacturer);
Methods in the remote service implementation (GreetingServiceImpl in this case) are intended to be called by client code, through the asynchronous interface. If you need to call them from server-side code, you are likely doing something wrong or not using it as it is intended to be used.
I can't tell you what you are are doing wrong without seeing more of your code, however. If you edit your question to show the code for your method implementations, we may be able to suggest a better way of achieving your goal.
I have an abstract TemporalModel class (annotated with #MappedSuperclass) that adds created and updated fields to all extending models. I want to add a getLatest() static method to it:
public static TemporalModel getLatest() {
return find("order by created").first();
}
When I put this method on the base class, and call it through a concrete class (Transaction.getLatest()), I get an error:
UnsupportedOperationException occured : Please annotate your JPA model
with #javax.persistence.Entity annotation.
I suspect this is because JPA doesn't in fact know I'm calling this method "through" the base class (there is no real static method inheritance in Java).
Is there another way to implement this method once, instead of repeating it on all entity classes?
Update - one way to achieve this (which I'm using in another heavier app) is described here (gist). In my current app, however, I wouldn't like to use repositories, and I wondered if there's another, lighter solution.
Constructors and static methods can never be abstract. The idea behind an abstract class
is to create blueprints of methods, that have to get worked out in the subclass(es). I suggest trying an interface TemporalModel instead of an abstract class, in which you create the method public static TemporalModel getLatest();
I haven't used this Play framework, so I'm not sure about the details here, but usually, when one does the stuff you want to do, in Java, one simply specifies the concrete class as a parameter to the static method in question. It's kind of ugly, of course, but it is Java.
I assume that this find method is a static method that is added somehow (by annotation processing?) by this framework on every extending class, right? In that case, I think your only recourse is to do something like this:
public static <T extends TemporalModel> T getLatest(Class<T> cl) {
try {
/* I don't know what type the find() method returns, so you'll have to fix the casting */
return(cl.cast(cl.getMethod("find", String.class).invoke("order by created").first()));
} catch(AllThosePeskyReflectionExceptions e) {
throw(new Error(e));
}
}
I think that's the best way available given the premises. I know it's ugly, so I'd be happy to be wrong. :)
I commonly find myself extracting common behavior out of classes into helper/utility classes that contain nothing but a set of static methods. I've often wondered if I should be declaring these classes as abstract, since I can't really think of a valid reason to ever instantiate these?
What would the Pros and Cons be to declaring such a class as abstract.
public [abstract] class Utilities{
public static String getSomeData(){
return "someData";
}
public static void doSomethingToObject(Object arg0){
}
}
You could just declare a private constructor that does nothing.
The problem with declaring the class "abstract" is that the abstract keyword usually means that class is intended to be subclassed and extended. That's definitely not what you want here.
Don't bother making them abstract, but include a private parameterless constructor to prevent them from ever being instantiated.
Point of comparison for those interested: in C# you would declare the class to be static, making it abstract and sealed (Java's final) in the compiled form, and without any instance constructor at all. That also makes it a compile-time error to declare a parameter, variable, array etc of that type. Handy.
I don't declare utility classes abstract, I declare them final and make the constructor private. That way they can't be subclassed and they can't be instantiated.
public final class Utility
{
private Utility(){}
public static void doSomethingUseful()
{
...
}
}
I would add more step beyond the private constructor:
public class Foo {
// non-instantiable class
private Foo() { throw new AssertionError(); }
}
Throwing the AssertionError prevents methods in the same class from instantiating the class (well, they can try). This isn't normally a problem but in a team environment you never know what someone will do.
As regards the "abstract" keyword, I have noticed utilities classes subclassed in numerous instances:
public class CoreUtils { ... }
public class WebUtils extends CoreUtils { ... }
public class Foo { ... WebUtils.someMethodInCoreUtils() ... }
I believe this is done so that people don't have to remember which utility class to include. Are there any downsides to this? Is this an anti-pattern?
Regards,
LES
By declaring them as abstract, you are in effect indicating to other coders that you intended for these classes to be derived from. Really, you're right, that there's not much difference, but the semantics here are really more about the interpretation of other people who look at your code.
As others stated, make a private parameter-less constructor. No-one can create an instance of it, apart from the class itself.
As others have shown how it is done with other languages, here comes how you do it in the next C++ version, how to make a class non-instantiable:
struct Utility {
static void doSomething() { /* ... */ }
Utility() = delete;
};
I think it's better to declare utility classes final with a private no-args constructor. Moreover all members of this class should be static.
An easy way to do all this in one statement is to use the #UtilityClass annotation of Lombok:
#UtilityClass
public class Utilities{
public String getSomeData() {
return "someData";
}
public void doSomethingToObject(Object arg0) {
}
}
If you use the #UtilityClass annotation you can skip the static keywords as in the example above since Lombok adds them automatically during compilation.
No, but if your language supports it, there's a strong argument to be made that in most cases they should (can) be declared as 'static'... Static tells the compiler that they cannot be instantiated, and that all methods in them must be static.
Abstract is for classes that DO have instance-based implementation details, which WILL be used by instances of derived classes...
someone mentioned that in C# 3.0 you could accomplish this via extension methods. I'm not a C# guy, did some back in the 1.5/2.0 days, but have not used it since then. Based on a very cursory understanding I think something similar can be accomplished in java with static imports. I realize its not at all the same thing, but if the goal is to just make these utility methods seem a bit more "native"(for lack of a better term) to the calling class, I think it will do the trick. Assuming the Utilities class I declared in my original question.
import static Utilities.getSomeData;
public class Consumer {
public void doSomething(){
String data = getSomeData();
}
}
Might I offer some constructive advice?
If you are doing a lot of this, there are two problems you will run into.
First of all, a static method that takes a parameter should often be a part of the object that is that parameter. I realize this doesn't help for objects like String, but if it takes objects you've defined, you could almost certainly improve the object by including your helper as a method of that object.
If it takes all native values, you probably could define an object that it's a method of. See if you can find any grouping of those native values and group them as an object. If you just try that, you'll find a lot of other uses for that little mini-object, and before you know it it will be amazingly useful.
Another thing, if you have a utility class with a bunch of semi-related static methods and static variables, you almost always want it to be a singleton. I found this out by trial and error, but when you find out you need more than 1 (eventually you will), it's MUCH easier to make a singleton into a multipleton(?) then to try to change a static class into a multipleton(okay, so I'm making words up now).
Good luck. This stuff was mostly trial and error for me--figured it out like 5 years ago though, and I've never found an instance where I regretted not having static class/methods.
Helper / Utility methods are just fine. Don't worry about adding them to a library inside your application or Framework. Most frameworks that I have seen use them in many varieties.
That being said, if you want to get really crafty about them you should look into extension methods in C# 3.0. Using extension method will make your Utilities a little more of a "holistic" part of your framework which it seems like what you're trying to do by considering to make them abstract. Not to mention extension method are a lot of fun to write!