Java methods flow - java

I'm trying to learn how to program on android which of course uses Java. I understand Java vaugely, but this confuses me.
A method which I view as a function (PHP being my native programming language) can seemingly be declared anywhere in a java file and still be pulled out at any other point is this so? What I mean is in PHP you have to define a function(method) to then be able to call it. So everything has to be in order.
Also is calling a function like including that section of code in your method calling it. Example being:
method 1 contains opendb command
method 2 contains closedb command
oncreate method calls method 1 then 2 does it act accordingly.
Sorry may sound dumb but I like concrete answers and not assumptions of mine.

The order in which methods are declared in java is of no importance.
Methods have no relationship to each other. You could invoke a method1 any number of times regardless of another method method2.
A sample could look like:
public DatabaseManager {
public void openConnection() {
// ...
}
public void closeConnection() {
// ...
}
}
Which you can invoke using:
DatabaseManager db = new DatabaseManager();
db.openConnection();
// do something
db.closeConnection();

A method which I view as a function
(PHP being my native programming
language) can seemingly be declared
anywhere in a java file and still be
pulled out at any other point is this
so?
Well, partially true :-). Java (like many other languages) has the concept of "visibility" of a method (functions are usually called "methods" in Java). If a method is private, it is only visible (and usable) inside the same class, if it is public is can be called from anywhere. See e.g. the excellent Java tutorial, which covers this: http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
However, unlike PHP, the order in which methods are declared inside a single class is irrelevant. You can call a method from the same class before the point/line of its definition.
Also is calling a function like
including that section of code in your
method calling it. Example being:
Yes, in the simplest case calling a method behaves like including that code in the place where the method is called. But there are important differences:
If you call a method, it cannot access local variables from the calling method, and class fields only if both methods are in the same class.
Java (being object-oriented) has polymorphism: You call a method on an object instance, and the method that is actually executed depends on the runtime type of the object instance, which may be different for different code paths. In that case calling a method is more complicated than just replacing it with the method's code.
Java methods can recursively call themselves; that wouldn't work if the compiler just included them where they are called.
So it's probably not really helpful to think of method calls as "like including the code"...

Your problem is not Java at all. It sounds like you have never programed the object oriented way. You should learn what a class is, what a method is.
I strongly recommend the basics for OOP itself: http://download.oracle.com/javase/tutorial/java/concepts/

In Java, your methods can be declared in any order in the class, for example
class A {
void C() { }
void B() { C() }
}
Could be equivalently declared as
class A {
void B() { C() }
void C() { }
}
Your second question is not very clear. But just to clarify - there is nothing like including in Java to execute another script - generally you will create new objects or run static methods of a class to accomplish things.

Max... I have not coded in PHP, but I have done a lot of scripting. According to the online docs that I found, PHP does not natively support events. So you are right, everything has to be "in order" in PHP. So you may need to get your head around moving from the sequential model of programming that I grew up with, and move to the event driven model used in Android Java.
You can divide your program into three parts. A view or presentation (main.xml). The controller or event handler (MyApp.java) and the algorithms, say model.java. MyApp.java has "event handlers" that basically sit around waiting to receive events so that you cannot absolutely know the order in which methods will be called. Do the heavy work in Model.java and write it so that it knows nothing of the view and is reusable.
So in UNIX model is the ENGINE and the view and controller is the INTERFACE. INTERFACE-ENGINE vs model-Controller-view.
Hope that helps,
JAL

Related

When are dot operators required?

When calling a method, I get that you have to use instanceName.method() or className.method(). However, in some cases the instanceName or className is omitted in the code and just method() is written.
Programming language is Java. Just covering this for the AP Computer Science test and I have relatively limited knowledge of coding outside of the parameters of the course so a easy to understand explanation would be greatly appreciated.
My book says something about client programs but I'm not exactly sure what it means (both in general and about client programs specifically).
I'll put my explanation as simply as possible - Usually you would use instanceName.method() when trying to effect the variables within a class. For example a "Cat" object, you could make a cat - Cat catOne = new Cat() and then use its methods catOne.setName("Kitty");. This will set this objects name to "Kitty", leaving all other cat objects with the ability to have their own unique name.
Using className.method() is done when using a static method within a class, eg public static int method(), and then using it in another class. This does not require you to instantiate an object for that class, and can use them willingly. For example, having a class called MathConstants and using something like MathConstants.getPi() ( Sorry for the crude example ).
When methods are called like methodName() , this means that the method is located within the class itself. Usually we use this , as in this.methodName(), but just using methodName() is okay.
Hope that is easy to understand

How to check when a method is run in another class in Java (method call listener)?

I am working on a program where I need to be able to check when certain methods are run on a particular object. I know that's probably a bit unclear, so here's an example.
Let's say that this is the class I am trying to access:
public class Clazz {
public void exampleMethod(ExampleParam param) {
//Unknown code
}
}
The Clazz object is not created by any of my code. I have no control over its creation.
The methods of Clazz (in this example, just exampleMethod(ExampleParam param)) are not called by any of my code.
What I need to do is have a way to determine when exampleMethod(ExampleParam param) is called by code that I do not have access to.
The code that is run inside the method is irrelevant to me. All I need to know is:
Every time the method is called.
If possible, the parameters that were passed into the method.
If on the off chance that the above is possible, it would also be useful to know the class that originally called the method.
In other words, is it possible to create a "method called" listener?
In Java, this is handled by "Aspect Oriented Programming" (also known as AOP).
AOP is included as part of the core spring framework, check there for more info.

How can I intercept a call from Java to Groovy--or simulate this easily

I was hoping to use groovy's invokeMethod to do this, but it turns out that when you call from Java to Groovy, invokeMethod isn't called, but otherwise it would have worked perefectly.
I have a case where I'm submitting a Groovy class to a Java class (Which I can't edit). The Groovy class is annotated and the Java class scans for the annotations and saves the annotated methods as listeners for it's events.
When the event is issued I'd like to grab some information from the event object, use it to retrieve data and inject that data into the event handler in the script (Via annotated variables inside that method).
The things I have control over--I instantiate the scripts, set a base class for them, and pass them to the other system to be registered. The scripts will be written by others--I have control over the script's design but my goal is simplicity.
I could probably create an adapter class, but that seems quite difficult and fragile since I'd have to manually register all those methods instead of using the annotations like it does now--there are a lot of different events to listen to.
I'm wondering if there are groovy tricks I'm not considering. I'm still pretty new to groovy meta-programming. Perhaps there is a way to create the adapter class automatically, or when I compile the scripts, replace the methods with forwarding methods that forward to my code before calling their real method--anything like that possible?
Requested source code:
Source code--well let's see, this process is spread across a few classes...
This is how I set up the Groovy Class Loader with a ScriptBase
cconfig.setScriptBaseClass("tv.kress.bill.minecraft.ezplugin.ScriptBase");
GroovyClassLoader gcl = new GroovyClassLoader(getClass().getClassLoader(), cconfig);
Then I pass it to the Groovy Scripting Engine (I'm leaving out some stuff here)
gse = new GroovyScriptEngine(cpString, gcl);
Then I instantiate the script
scriptClass = gse.loadScriptByName(file.getAbsolutePath());
instance = (GroovyObject) scriptClass.newInstance();
Then, if it's a "Listener" which is the marker interface that the "canned" java library uses to identify java classes it should scan for annotations, I pass it off to that class so that any annotated methods can be registered (Somewhere along the line "instance" became "script", same object though:
if (script instanceof Listener)
pm.registerEvents((Listener) script, this);
The interesting part of the script itself looks like this:
#EventHandler
public void userEvent(UserInteractEvent event) {
What I'd like to add is the ability to, inside the userEvent, add an annotated local variable like this:
#Persist int persistedPerUserData // Or #PersistPerUser? or #Persist(User=true)?
so that just before userEvent is called, I can intercept it. I'd grab the user name from the UserInteractionEvent, combine it with the script, variable and method name to get a unique signature like "MyScript:UserEvent:Bill:persistedPerUserData" and use that to retrieve an int I can place into persistedPerUserData.
Later after the method returns grab the value from persistedPerUserData and store it back into "MyScript:UserEvent:Bill:persistedPerUserData" (Currently a hash but I expect to make it a database eventually).
In this way, the script never has to consider the fact that it's dealing with different users, it just has to have a single set of variables and all the persistence just works.
There are other events this will work for, but I believe they all extend the same event and that root event has the "user" field.
EDIT: Just as another thing NOT to try, I tried to use the ProxyMetaClass/interceptor like this:
// Attempt (and fail) to intercept calls to an instance of clazz
class Slicer {
public static Object slice(Class clazz) {
Object instance;
def proxy = ProxyMetaClass.getInstance(clazz);
proxy.interceptor = new MyInterceptor();
proxy.use {
instance = clazz.newInstance();
}
return instance;
}
}
With the same results, every call from a groovy class was instrumented fine, but no calls from Java were intercepted. Back to the drawing board. I guess this is why Aspects use bytecode manipulation.
I really haven't figured out an answer to this, but I came up with something that I think will work--I suppose nobody mentioned it because it was so obvious, but I'm still "Thinking in Java" More than groovy.
Okay, where I was hoping for the script implementation to look something like this:
#EventHandler
public void userEvent(UserInteractEvent event) {
#Persist int persisteData
// At this point persistedData contains data different depending on which user was passed in
...
I think that if I use a closure I think I can do something close:
#EventHandler
public void userEvent(UserInteractEvent event) {
persistScope(event.user) {
#Persist int persistedPerUserData // Or #PersistPerUser? or #Persist(User=true)?
...
and that way within persistScope I can scan the closure for #Persist annotations and do my thing. This may not work exactly because that int hasn't been created until the closure starts, but I think I can fix that using the methods I mentioned in the question as long as I'm calling from groovy to groovy. Either that or I'll just make "it" a hash with the persisted user data.
It's slightly more awkward but I think it will work, and I like the fact that it's a little more explicit (In fact before I was just assuming that the "event" passed in had a .getUser() method, now I can scope persistence to anything I want).
I'll go try to implement this and give it a few days to see if anyone comes up with an answer to the original question I asked before accepting this.
EDIT: I'm unhappy with this solution. Since the variables are declared inside that scope I couldn't use the #Persist annotation, so i passed in a hash that the module can use as a data container, then I persist it after the closure returns.
Still looking for better answers...

How to change a method's behavior according to the application which is calling it?

I have a common jar that uses some unmarshaling of a String object. The method should act differently depending on which application it is called from, how can I do that besides from the fact that I can identify the application by trying to load some unique class it has (don't like that). Is there some design pattern that solves this issue?
As I alluded to in my comment, the best thing to do is to break that uber-method up into different methods that encapsulate the specific behaviors, and likely also another method (used by all of the app-specific ones) that deals with the common behaviors.
The most important thing to remember is that behavior matters. If something is behaving differently in different scenarios, a calling application effectively cannot use that method because it doesn't have any control over what happens.
If you still really want to have a single method that all of your applications call that behaves differently in each one, you can do it, using a certain design pattern, in a way that makes sense and is maintainable. The pattern is called "Template Method".
The general idea of it is that the calling application passes in a chunk of logic that the called method wraps around and calls when it needs to. This is very similar to functional programming or programming using closures, where you are passing around chunks of logic as if it were data. While Java proper doesn't support closures, other JVM-based languages like Groovy, Scala, Clojure, JRuby, etc. do support closures.
This same general idea is very powerful in certain circumstances, and may apply in your case, but such a question requires very intimate knowledge of the application domain and architecture and there really isn't enough information in your posted question do dig too much deeper.
Actually, I think a good OO oriented solution is, in the common jar, to have one base class, and several derived classes. The base class would contain the common logic for the method being called, and each derived class would contain specific behavior.
So, in your jar, you might have the following:
public abstact class JarClass {
public method jarMethod() {
//common code here
}
}
public class JarClassVersion1 extends JarClass {
public method jarMethod() {
// initiailzation code specific to JarClassVerion1
super.jarMethod();
// wrapup code specific to JarClassVerion1
}
}
public class JarClassVersion2 extends JarClass {
public method jarMethod() {
// initiailzation code specific to JarClassVerion2
super.jarMethod();
// wrapup code specific to JarClassVerion2
}
}
As to how the caller works, if you are willing to design your code so that the knowledge of which derived class to use resides with the caller, then you obviously just have the caller create the appropriate derived class and call jarMethod.
However, I take it from your question, you want the knowledge of which class to use to reside in the jar. In that case, there are several solutions. But a fairly easy one is to define a factory method inside the jar which creates the appropriate derived class. So, inside the abstract JarClass, you might define the following method:
public static JarClass createJarClass(Class callerClass) {
if (callerClass.equals(CallerClassType1.class)) {
return new JarClassVersion1();
} else if (callerClass.equals(CallerClassType2.class)) {
return new JarClassVersion1();
// etc. for all derived classess
}
And then the caller would simply do the following:
JarClass.createJarClass(this.getClass()).jarMethod();

Java static reflection on subclasses

I am implementing a sort of ORM in Java. I am trying to do a static find method that is only in the parent class. Let me get to the point:
public class DB {
public static Object find (int id) {
// i want to return anew instance of the calling subclass
}
}
public class Item extends DB {
// nothing here
}
public class Test {
public static void main () {
Item i = (Item) Item.find(2);
...
}
}
I don't know how to have the find method know which of its inherited class is calling it, so that i can return the right instance (and maybe call the right constructor, etc.) And the inherited class could be anything, no limit.
I've tried stacktrace, but it's only traced from Test to DB.
Any ideas?
Thank you everyone!
Static methods are not inherited, so you can't do this. A common approach to this problem (not including using one of tons of available ORM solutions) is to split your class hierarchy into two:
"Entity" (e.g. classes representing your actual data)
and "DAO" (Data Access Object) - classes that contain methods to manipulate data persistence.
A word to the wise: It's probably a bad idea to try and implement your own ORM. Projects like hibernate have covered this task in great detail, so if you roll your own you are likely to reinvent the wheel and possibly attempt to solve problems that have already been solved.
More on topic, ChssPly76 is correct in that you cannot accomplish this because of how static methods are handled in Java. When the VM loads the bytecode for the static method invocation, it will perform a lookup to find where the method actually is located. It won't find it on the Item class, so it will instead bind the call to DB.find.
However! It may be possible to achieve what you are trying to do with some bytecode wrangling. Viewing the bytecode (using javap -c) for the static method call in your example, we get the following:
invokestatic Method Item.find:(I)Ljava/lang/Object
Thus, once your call reaches DB.find, you could follow the stacktrace back to the callsite, and then inspect the bytecode at the callsite to retrive the actual target of the call. In theory, anyway, as I haven't seen this myself in practice. Also, beware of hacking bytecode like this, for here be dragons.
Kudos for identifying the active record pattern, and wanting to use it in Java. I do agree it's a design pattern that makes more sense than most DB access patterns found in Java, and it's one of the strengths of Ruby and PHP.
I think you may find the "Generic DAO" article at IBM developerworks useful.
Short: use Generics wisely.

Categories

Resources