Closure in Java or something like it - java

I have been trying to find a way to incorporate something similar to Closure in Java 1.6 since I'm developing for Android.
What I want (in a perfect world) I have a class, we will call it "Item".
I then have an arrayList of these.
ArrayList<Item> items = new ArrayList<item>;
In each one of them items.get(x) I want to save a block of code that will be executed when called. This block of code needs to take place in the scope of the class housing the ArrayList items.
My only, half brained idea, would be to create the methods in the class that housed "items" and save the name of the function in each of the "item" instances, then use reflection to call those methods....
I'm pretty doubtful that this could be possible, but this is the place I will find an answer either way.
Thanks ahead of time for any help.

What you need is an interface like
interface Closure{
public void exec();
}
and create an anonymous class for each "closure" code you want
Closure closure = new Closure() {
public void exec(){
// code here
}
}

Related

How do I call to a void method to incorporate it in a method in a different class?

My assignment is to create a program that simulates a simple online shopping program.
we have to:
create a main menu with 3 options and then a submenu when selecting the 2nd option on the main menu.
I'm unsure how call a method from another class for example:
I have been given a method:
public void start() {
which is in the file "GroceryStore.java"
I am supposed to create a topMenu method which when the user inputs "1" calls to the method:
public void displayItems(){
^in file called "Stock.java"
which then prints out an array of items that online store has in stock. The array in the
Stock.java is
private SalesItem[] items;
Can anyone tell me how to do this? I have to do this for several things and I'm hoping I can apply the skeleton of this to the rest of the cases.
For now, I'm going to assume that Stock is an instance type(it sounds like an instance type), and It would make sense that your GroceryStore would have a reference to 1 or more Stock items.
Your Stocks will have to be instantiated with the new keyword. so
Stock myStock = new Stock(/*parameters for constructor*/);
after you do that, you can call the displayItems method of myStock like so
myStock.displayItems();
so start() is in the GroceryStore class.
So in a public static void main class you would go :
GroceryStore gs = new GroceryStore();
gs.start();
In your GroceryStore class you would have a new method which looks like (You may want to have the Stock stock = new Stock() line in the constructor of the GroceryStore object-- would make more sense:
Stock stock = new Stock();
public void topMenu(int parm){
if(parm==1)then{
stock.displayItems();
}
}
And then finally in the Stock class you have the displayItems method which may look like :
public void displayItems(){
for(int i=0;i<items.length;i++){
SalesItem temp = items[i];
System.out.prinlnt(temp.toString());//or this may be temp.getName() or whatever returns a string from this SalesItem object - I dont know what it looks like - you never said!
}
}
It is however essential you actually understand what is going on here not just copy paste and run?! This wont actually do anything anyway until you have a call to the topMenu method passing it 1, so you will need to workout how you are going to interact with your gs object whether its by keyboard input, mouse click on a gui or something else :)
To call a method outside the current instance you have multiple options:
make the method static (so that it won't be attached to any particular instance) and call it through MyClass.method(), this has sense if it is a stateless object, mostly an utility method
create a static instance variable that can be accessed (so method is not static but the specific object is), then call it through SomeClass.stock.method(), this has sense when you want a single object of a specific type throughout the program
create a normal instance variable inside the class from which you want to call the method (this has sense just if the object contained is used in a HAS-A relationship). Then you call it simply doing this.stock.method() (you can omit this)
You need to tell the compiler where to get the methods from if the method is not in the same class. The best way of doing this would be to create an object that refers to the class you're trying to reach (using the New Java keyword and the appropriate syntax, i.e. ClassName objectName = new ClassName() - you may want to include any parameters you may have).
Have a look at this other StackOverflow answer - the user had a question very similar to yours, so it may help.
Also, there is a pretty good tutorial on objects and classes on TutorialsPoint. I suggest you have a look at it and give it a go. Try understanding the concept behind what you're trying to achieve first - I can guarantee you it will help later on as this is a very fundamental concept in OO programming.

What Is “the Interface” And How Do I Program “Against” It? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
ArrayList<Class> name = new ArrayList<Class>(#)
Someone told me yesterday that something like this is bad practice, and that I should program “against the interface”, like this:
List<Class> name = new ArrayList<Class>(#)
What did he mean?
ArrayList implements List. So, best to use List for a number of reasons. For example, if you wish to change the type of list (e.g. you decide to use a LinkedList, Stack, or Vector) in the future, you need only change the right side of the assignment and the rest of the code just works, unchanged.
There is no need to reveal what exact implementation of List you're using.
The only methods that are available to you are the methods from the interface. Technically it doesn't matter a lot, but it's a good habit to follow. The code is cleaner and easier to maintain.
The "interface" in that code snippet is List being a more abstract class than ArrayList.
List will be implemented by a number of other classes like ArrayList, LinkedList etc...
By using the interface to declare name, then the users of name do not have to know which type of list name actually is, and if you decide to use a different type of List in future you can without having to change lots of places within your code.
List<Class> name = new ArrayList<Class>(#)
SuperType ref = SubTypeObj
This is polymorphic way of creating an ArrayList. List is a super type of ArrayList.
The advantage of creating the arraylist like this is:
you could later refer the same list to create a LinkedList.
name = new LinkedList(#)
Ideally, you want to use the interface of a collection rather than the implementation for Collection variables and return values. In your example, it's not that big an issue. Where it does become more useful is when writing methods:
public List<String> doSomething() {
}
By using List<String> and not ArrayList<String>, this method could choose a different list to use (it might change to LinkedList for example), but the contract of the API wouldn't change, so all the calling code would still work, even though the method now returns a different type of List.
In Interface defines what methods are available, so when a class is written to implement an interface, it must have the methods defined in the interface. (it may have other methods as well)
Suppose you write a class which other people will use, and it has a method like this:
public void doSomething(List<Thing> aListOfThings) {
//some code to manipulate the list
}
When other people write code to use your class, you don't care exactly what type of List they've used to call your method. All of these are valid:
yourClass.doSomething(new ArrayList<Thing>());
yourClass.doSomething(new AttributeList<Thing>());
yourClass.doSomething(new Vector<Thing>());
yourClass.doSomething(new SomeOtherTypeOfList<Thing>());
They are free to choose whatever type (implementation) of list is suitable for their purposes.
He meant that you should use only the very type of the variable you need. For example, unless you are using methods that are only defined on ArrayList then you should use List. Likewise, if you don't need anything that comes from List then use Collection etc.
There are two reasons for this:
1) It makes it easier in the future to change the implementation to another type. Lets say you are using some ORM that uses a LazilyLoadedList, well if all your code is against List then you can slot it in painlessly. If it is against ArrayList then you need to change lots of method signatures and make sure that you aren't depending on a ArrayList specific methods. This is part of what
2) Interfaces are easier to mock using tools like JMock or Mockito.
This should help you understand what an interface is and how it is useful in software development.
Let's say you need to mail a package to someone. There are many carrier options: USPS, UPS, FedEx, etc.
Now imagine if there was one , central mailbox you could drop your package into and all carriers could deliver from that mailbox. So, you don't care how it gets picked up by USPS, UPS or FedEx. All you need to do is bring your package to the mailbox and drop it off. How it actually gets delivered is irrelevant to you.
In this example, you could have an interface defined as:
public interface IMailService
{
void SendMail(obj myMailObj);
}
And then you could have concrete implementations of MailService defined as:
public class USPSMailService : IMailService
{
public void SendMail(obj myMailObj)
{
//This code executes SendMail using USPS' implementation
}
}
public class UPSMailService : IMailService
{
public void SendMail(obj myMailObj)
{
//This code executes SendMail using UPS' implementation
}
}
public class FedExMailService : IMailService
{
public void SendMail(obj myMailObj)
{
//This code executes SendMail using FedEx's implementation
}
}
Then, when you want to send mail in your code, you would write it like this:
IMailService mailService = new FedExMailService();
mailService.SendMail(myMailObj);
If you later need to use UPS' mail service, then all you'd need to do is instantiate with the UPS type. The rest of the code, including all calls to SendMail() remain unchanged:
mailService = new UPSMailService();
Now, if UPS offers some service that the other carriers do not, then you would need to define the variable as the concrete type.
For example, if the UPS class was defined as such:
public class UPSMailService : IMailService
{
public void SendMail(obj myMailObj)
{
//This code executes SendMail using UPS' implementation
}
//This is a method that only UPS offers
public void SendMailOnSunday(obj myMailObj)
{
//This code executes UPS' proprietary method
}
}
Then your code would need to use the concrete class as such:
UPSMailService mailService = new UPSMailService();
mailService.SendMailOnSunday(myMailObj);

Java string with name of class to class

Sorry about the strange topic name, could not find one that fitted well.
To my problem, i want to create something dynamic in Java, it is a very simple class that can take an event and throw it along, sadly have the system i am using be made so each event must have it own method where the event is the argument of the method, but the good news is that we can add as many event listener classes as we want! I wan my program to be able to dynamic add and remove the methods that are being listened to, by add and remove the listen classes.
I am not good with Java but have a fair deal expirence with C#, so i attacked my problem as i would there and created this class.
public class TESPluginDynListener<T> implements Listener {
TESPlugin plugin;
public TESPluginDynListener(TESPlugin plugin){
this.plugin = plugin;
}
#EventHandler(ignoreCancelled=false, priority = EventPriority.LOW)
public void onDynEvent(T event){
if(event instanceof Event)
plugin.onEvent((Event)event);
}
}
This seems to work fine, but my problem is, that the event i have to register do i get as a String, example "some.package.someEvent", and i have no idea how to translate that into the Type T so i can add the listener class.
So how can i create an instance my class TESPluginDynListener where T is translated from a String? I am not interested in doing a lot of if else, as i want this to be as dynamic as possible!
Here is an idea of what i am trying to do
String eventClass = "some.package.someEvent";
TESPluginDynListener listener = new TESPluginDynListener<Type.FromName(eventClass)>(this);
eventhandeler.RegisterListener(listener);
It sounds like you're looking for Class.forName and Class.newInstance.
On the other hand, bear in mind that type erasure in generics means you don't really need to know T in order to build a TESPluginDynListener... you probably want to take Class<T> in the constructor for TESPluginDynListener and use Class.isInstance rather than instanceof within onDynEvent.

Android / Java - How do I call upon a function in a separate *.java file?

I do an import of the full package name / java file, and if I do a <classname>.<method>, SOMETIMES I can get it to access - other times I get a lot of can't use a static in a non static bunch of talk.
I'll admit I'm new to Java, so what do I need to do? Call a class instance first, then call my methods? I'm rather confused by this, as I want to put all of my 'functions' into a FunctionsList.java file, and all of my main Activity (UI) into a MyActivity.java file.
For example:
<MyActivity.java>
import com.example.FunctionsList;
private class MyActivity extends Activity {
FunctionsList.function();
}
9/10 times I get that static/non-static error.
If I put all of my functions into MyActivity.java, I have zero problems! Anyone help me on what I presume is a basic Java newbie issue?
Here's an example that will hopefully help you out a little.
public class MyFunctionClass {
public String myFunction() {
return "This is an instance function.";
}
public static String myStaticFunction() {
return "This is a static function.";
}
}
Then in your activity you have something like this.
public class MyActivity extends Activity {
#Override
public void onCreate() {
// If you want to call your static function, you do not
// require an instance of a MyFunctionClass object.
String myStaticString = MyFunctionClass.myStaticFunction();
// If you want to call your instance function, then you need
// to create a MyFunctionClass first.
MyFunctionClass variableName = new MyFunctionClass();
String myInstanceString = variableName.myFunction();
}
}
As Jon mentioned, you'll probably save yourself some frustration if you read up on object-oriented programming before diving in. There are some basic things that a new programmer will need to understand before diving in. Good luck!
If you want to use a non-static method, you have to have an instance of the class to call the method on. If you want to use a static method, you don't need an instance.
As an example, suppose you tried to call String.length() - what could that return? It's trying to find the length of something, but you haven't specified which string you're interested in. The same is true for other instance methods - the results will usually depend on which object you're calling them on, which is why they're instance methods to start with.
As an aside, I would strongly recommend you to learn the basics of Java first, before trying to use Android. That way when you get into genuinely tricky problems, you won't have to wonder whether it's part of Android or whether it's a simple Java error. See my answer on a related question for more advice about this.

What does that Java construct do?

I new to java so bear with me if this is a ridiculously simple question but I am curious about this method call which has {code} being taken in - see code below for an example in the method addSelectionListener. What is the purpose of this? I have been looking through docs for an explaination but cant seem to find what this practice is called never mind any useful information.
setStatusLine.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
String message = "I would like to say hello to you.";
if (pressed) {
message = "Thank you for using me";
}
setStatusLine(message);
pressed = !pressed;
}
});
Thanks for any help or insights that can be offered
this is an Anonymous Class, or Anonymous inner class. If you google for that you will find some tutorials/examples. Sun has some docs too.
As the other contributors already said: It is an Anonymous Class
You could have created a new class named MyClass in a new file called McClass.java looking like that:
class MyClass extends SelectionAdapter {
public void widgetSelected(SelectionEvent e) {
<your code that's being executed whenever the widget is being selected>
}
}
Then you could have changed the first line like that:
setStatusLine.addSelectionListener(new MyClass());
See? Now you have an "explicit" class with just one function. Often that is too much overhead and would clutter your design.
Does that help?
The method addSelectionListener receives a SelectionListener instance. It doesn't receive "code". The confusing thing is the use of new <class/interface name>(){...}. This construct is used for anonymous inner classes. In fact what the code above does is extending the SelectionAdapter class, overriding its widgetSelected method, creating an instance of the new class and passing it to addSelectionListener().
Usage of anonymous inner classes is common with listeners, where we create a new class, to be used in one specific place. Therefore we don't give it a name, and we prefer implementing it directly in the context where it is being used.
There is not a method call in fact...
This code set a selection listener on the setStatusLine component.
An equivalent of this code could be
public class X implements SelectionListener{
//In the constructor or an other method.
setStatusLine.addSelectionListener(this);
public void widgetSelected(SelectionEvent e) {
String message = "I would like to say hello to you.";
if (pressed) {
message = "Thank you for using me";
}
setStatusLine(message);
pressed = !pressed;
}
}
It took me some time to understand Anonymous Inner classes. The basic things to remember are:
They are just like parameters, except instead of passing in an primitive or Object you pass in a class that implements an Interface/extends a class (yes they also work with interfaces) depending on method parameter.
They are anonymous, so "disappear" right after the method has popped off the stack.
}); is a dead give-away for an anonymous inner class.
They often pop-up in user interfaces for listener events
They save clutter in your code, but also make it harder to read.
For full punishment read the JLS: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.9.5
If you are interested in knowing the nitty gritty about such things, reading the SCJP book and doing the exam is good or you can study the JLS. It won't learn you how to code, but it will help you understand how Java, and in some way, many other OO languages work.

Categories