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.
Related
The details:
I have been given a Java program in which I need to fill in some code. The main idea of the program is to get used to interfaces and static methods in them. For the past 6 hours I have been watching countless of videos regarding interfaces and static interfaces and I still feel somewhat clueless to what I am supposed to do.
public interface Util {
static Util create() {
//TODO: this line needs to be replaced with the constructor of a concrete implementation
throw new IllegalStateException("Not implemented yet!");
}
Instruction forSymbols(Symbol first, Symbol last);
Symbol forToken(String token);
Supplier<Integer> buildPipe(InputStream input);
Consumer<Integer> buildPipe(OutputStream output);
String getInstructionCode(Instruction instruction);
Optional<Instruction> getInstruction(String code);
}
This is a snippet of the util interface for a program that will be relevant for having a Ook! translator and is supposed to have a lot of useful tools for other classes.
Now, my goal is to understand what I am supposed to do.
What I tried:
Considering I don't know what I need to do, I don't know what I have to code. I understand that an interface is a sort of template for classes. A static method in an interface is the part that I don't understand yet: I have been told that a static method in an interface is something that doesn't have to be implemented in other classes. In my case, the static method create() is "supposed to be a concrete instance of the util object". So, if I get this right, due to it being static, there would be one shared instance of util.
Afterwards, if a class has the prompt "Instruction instruction = util.forSymbols(Symbol.Point, Symbol.Point);" after Util.create() has been used, I would have defined instruction using util's forSymbols method.
I do not know if I am good at conveying just what I need. I per sé understand what a constructor is, I understand what an interface is, I understand what static does, but I don't understand what I have to insert into the create() method. Heck, I don't even want a direct code solution to my problem, I just want to understand what I am supposed to code.
That being said, if anyone could give me an example of an interface working in a similar fashion as my code above that makes it clear just what exactly the static part in an interface does aswell as help me out with my describes issues, I would be tremendously thankful. Also, I hope that my issue description is alright.
That being said, thank you for trying to help me and thanks to all possible answers.
No, the interface can't keep state, so there isn't anywhere for the shared instance to hang out. This is not a way to implement a singleton. It must be a factory method. I think adding a method like this is confusing and probably a bad idea because it ties together the interface and the implementation in an inflexible way. you're expected to create something that implements Util, so there is going to be a constructor call for that class implementing Util. Otherwise it's not clear.
Another sign this is a bad idea is obviously Util doesn't have any instance methods so isn't usable as an object; either a) there is no state and creating an object is pointless or b) the object returned has to be cast to something else to be useful. Casts are bad, for the most part; they mean we're not benefiting from using the type system.
An interface is like a mask an object wears to keep users of it from seeing anything on it except what is on the interface. But allowing static methods is kind of a bolted-on feature that doesn't have much to do with interfaces (except that classes that implement the interface can call them without having to reference the interface).
Originally in Java you could put static methods only in classes, not in interfaces. There was an idea of a utility class, which was just a dumping ground for people to put static methods, and which didn't have any purpose as a class otherwise. Then there was a change to the language so you can put static methods on interfaces and not have to have a class involved. That's all putting static methods on an interface buys you, you can add only static methods because there is no mutable state allowed.
These methods outlined for you should all be things you can implement with only passed in arguments and local variables, without keeping any state outside of the scope of the method implementation.
I've tried to give you some idea of what is possible and what isn't, once that is clear you can ask your instructor some more focused questions about what you need to do.
I agree with Nathan Hughes. This an ill-conceived design, on the face of it.
But to cut to the chase, here is an example of you could complete that static method:
static Util create() {
return new OookUtil();
}
where
public class OookUtil implements Util {
public OookUtil() { ... }
// methods implementing the Util API for the Oook case.
}
Reviewing this we can immediately see one of the problems with the interface design. We have hard-wired a specific implementation class into the interface. That is most likely a bad idea.
Could we do any better? Well ... maybe ...
The Java SE class libraries have a concept of a Java Service Provider Interface or SPI. An SPI allows different providers to be selected depending on what is available at runtime, and so on. The idea is that SPI code does a runtime classpath search looking for all classes that implement the SPI (e.g. your Util). Then it selects the "best" according to (typically) runtime configurable criteria.
That logic would be implemented in your create method. The method would then instantiate the chosen class reflectively and return the instance. In its simplest form (ignoring the classpath search aspect) it might be something like this:
static Util create() {
String classname = System.getProperty("yourapp.utilclass");
Class<?> clazz Class.forName(className);
return (Util) clazz.newInstance();
}
In this illustration are getting a classname from the system properties. It could be set by running the application with a -D option; e.g. -Dyourapp.utilclass=yourapp.OookUtil.
The above code needs some exception handling ... which I will leave for you to figure out.
Maybe that is what your instructor is getting at. But if so, he or she should have explained more clearly what was expected.
I have following scenario, and a confusion to have instance method or static method for dbhelper?
We have a dbhelper class which as name suggest help other classes to work with MySql db.
The db helper class will be used by 2 independent module.
Java Webapp.
Windows based Java app
Currently all the methods in dbhelper class are instance methods
There are 8 methods in dbhelper class among which 3 will be common for webapp and windows app and rest only used by webapp.
Windows app is kind of continuously running 24*7.
Our confusion is such that if we keep methods as instance methods, then we have to crate object of dbhelper class and eventually will be always alive as used by windows app.
What I see advantage of keeping methods as static is no object required.
Note:
I know how static and instance method works.
Google search do not help for this specific example.
The question is too broad for a specific answer. But I can answer with the kinds of things I'd be thinking about, in general.
First of all, if your static methods are going to save state in static class variables, that's not good practice. If there's any state involved, you definitely want to make them instance methods, so that an object of that instance will be holding the state.
You mention that your methods are there to help work with a database. How are they going to access the database? If the database isn't passed as one of the method parameters, then that means the reference to the database has to be stored somewhere, and I think it's best if the dbhelper is an instance that stores a reference to the database (or a reference to some other object that can be used to retrieve the database object) as one of the instance fields.
So I'm going to assume that the methods take a database parameter, or a parameter to some other object that will give you the database object. Given that, there are two things I'd think about when considering whether to make your methods static.
(1) What is the likelihood that the method will change because the requirements change? If it's at all likely, then I'd definitely lean toward making the methods instance methods; in fact, I'd consider making "dbhelper" an abstract class or interface, and having different implementation classes implement the abstract methods in different ways when something changes. That seems to me to be more flexible than just having one static class whose code has to change if the business logic changes. It lets you switch back and forth, or even lets you switch the logic dynamically at run time.
(2) Will you want to mock the method for testing? If your methods access a database, then you will probably want to provide a mock version of the method when unit-testing other classes that call the method, since you want to be able to test them without worrying about setting up the database access and everything. This would also argue for making dbhelper abstract or interface, so that you can provide a mock implementation in addition to your real implementation. (However, some testing platforms like JMockit will let you mock static methods.)
Those are the kinds of things that would lead me toward making the methods instance methods. If you're sure that they don't apply, then it should be OK to make them static methods.
Instead of using static, make use of Singleton design approach for dbHelper class.
something like this,
public class MyDBHelper {
private static MyDBHelper instance;
private MyDBHelper(){}
public static MyDBHelper getInstance(){
if(instance == null){
instance = new MyDBHelper();
}
return instance;
}
public void addRow() {
........
}
}
From other classes, you can access the methods like below
MyDBHelper.getInstance().addRow();
1st : Make all methods of class dbhelpe static and load them when your application gets loaded by any web/application server.This task can be accomplished by static block .
2nd : try to implement Singleton pattern on your dbhelp class ,so that only one object of your class can be shared,this will not leads your application to create object many times,and your application will work faster.
First of all, methods in one class used by multiple callers (web app and Windows app) suggests violation of SRP, so you should be dividing the single DB helper into multiple classes.
Secondly, there are advantages and disadvantages of static and instance methods.
If you practice TDD or DI, it discourages static methods as they are non-mockable (unless you use a framework like Powermock which to me seems a bit hacky.)
If you only do end to end testing, its okay to use static methods.
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.
I'm writing some kind of library. I have an abstract class there. Client-code needs to extend it to use some methods. May happens that user quits application and after he restarts it I need to restore reference to his concrette class. My idea was to save canonical name of user's class and then just make newInstance() for it. However for some reason it can't create the instance. I've made a test:
void foo(AbstractClass a) {
String classname = a.getClass().getCanonicalName();
System.out.println(classname); //Output: "com.test.clientcode.Main.ConcretteClass"
a = null; // here I lost my reference to ConcretteClass for example, so all I have is a classname
Class.forName(classname).newInstance(); //Throws exception: "java.lang.ClassNotFoundException: `com.test.clientcode.Main.ConcretteClass"
}
It's a method within library code. For argument a I give it an instance of concrette user class.
UPDATE: to make things easier: in my library I have a method like above, argument a is a reference to client's ConcretteClass as we see in the output of 2nd line. Then I lose my reference. How can I make a new instance of ConcretteClass if the only thing I know is ConcretteClass' canonical name?
Your approach won't work.
If you want to "restore" the instance you should do in other way instead of simply newInstance. this is one thing. I don't know your concrete requirement, so I cannot answer further on the "restore" part.
I said your approach won't work, because you said your are writing a "library", so I guess client code will import your class, that is, your abstract class is in client codes's classpath. however, the client class won't be in your classpath. that's why you got the classnotfound Ex.
same as if I extend a class from guava for example, how come in guava codes, it knows my class and create an instance of my class?
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().