I'm trying to accomplish passing a method in Java.
Here is the birds-eye-view of what I'm trying to do as a dummy example:
public final class A {
private String value;
public A(String value) {
this.value = value;
}
public final Object bind(Function<String, String> func) {
this.value = func.apply(value);
return this;
}
// Rest of the logic here to deal with `value`
}
public final class B {
public static void main(String[] args) {
A<T> a = new A("hello");
a.bind(B::methodOne).bind(B::methodTwo);
}
private String methodOne(String s) {
// method logic here
return "haha";
}
private String methodTwo(String s) {
// method logic here
return "hi";
}
}
So, basically, I've methods in a class, B in the above example, and I want to pass the methods of B to A and store the return value of that method of B on A for further processing.
I've tried to make use of method reference feature of Java but since I don't code daily with Java, I'm having a hard time getting my head around how to properly accomplish this while fulfilling the constraints above.
Currently, I'm getting a incompatible types: invalid method reference error while I do the binding in the main method.
Update
Made changes on my constraints of the program.
EDIT: The asker updated their question a lot after reading this answer. Crucially, originally each method had a completely different signature (different param types and amounts, and different return types). I'm leaving this answer untouched, be aware it is no longer particularly relevant to the question as it currently stands.
This doesn't work well because the methods you want to pass have completely different signatures (methodOne's is (B, String) -> int (why do you have a capital I Int in there, is that a typo?), methodTwo is (B) -> String, and methodThree is (B, String, String) -> String.
In java lambdas must fit a functional interface. It is not possible to have a functional interface for a variable number of input arguments.
With generics you can attempt to paper over the fact that the types of your inputs and output are different every time.
This really sounds like an X/Y problem: You have problem X (which you didn't explain and we don't know what it is), and you thought: I know! I'll use lambdas to abstract away the notion of 'a method'... and now you're asking questions about that.
But you're asking the wrong question. Ask X. Because even if hypothetically you could somehow fit your 3 methods all in the same lambda type (you can't), you would not then be able to invoke them.
Here's one more workable notion, but I have no idea if it solves your X because you didn't explain this:
#FunctionalInterface
public interface MyXThinger {
Object result(Object... args);
}
If you want to invoke this, how would you know that the particular MyXThinger (you didn't explain what X is, so I can't come up with a good name here) works if you pass 2 strings, and crashes if you pass anything else? That's.. more or less why I find your problem description insufficient to give solid advice here.
You're writing the expression B::methodOne in a static context.
non-static methods have an invisible parameter, called 'the receiver': It's the instance.
So, in a static context, B::methodOne has the signature: (B, String) -> String. What your bind method wants is (String) -> String, and these two are not compatible. Therefore, this does not work.
There are two ways to fix it:
create an instance: B b = new B(); a.bind(b::methodOne);. The expression b::methodOne, where b is a variable of type B referencing an actual instance of B (as created with new B()) DOES have the signature (String) -> String as required.
Make the methodOne method static, at which point it no longer has the invisible B instance parameter.
Your code is also littered with rookie mistakes; you must call a.bind and not A.bind, using A and B as class names is extremely confusing, your bind method returns Object (it should return A), etc. The way to fix those is to learn basic java, I think; trying to tackle those mistakes bit by bit seems unsuitable for what stackoverflow is for. Thus, I leave those as an exercise for you.
Related
How can I fix this problem?
rv_groupAddMember.setAdapter(new GroupAdapter(groupModelList, position -> {
selectedGroup = groupModelList.get(position);
addMember_groupName.setText("Seçili Grup :"+selectedGroup.getGroupName());
}));
public class GroupAdapter extends RecyclerView.Adapter<GroupAdapter.GroupViewHolder>{
List<GroupModel> groupModelList;
OnClickItem onClickItem;
public GroupAdapter(List<GroupModel> groupModelList, OnClickItem onClickItem) {
this.groupModelList = groupModelList;
this.onClickItem = onClickItem;
}
I added my GroupAdapter class and constructor
error
I'm watching tutorial everything is the same and there shouldn't be an error.
The problem is, java needs to figure out what the lambda is actually trying to be, and only then can it know what the type of position is. For example, given:
void foo(Consumer<String> x) { ... }
If you then write: foo(s -> System.out.println(s)); - java knows that the type of s is String only because of this sequence of events:
There is only one foo method.
That method takes a param of type Consumer<String>.
That type is a functional interface (an interface with a single method), and that method's signature is void accept(String t).
The lambda is an implementation of that method, therefore, s must be String.
And only then can java continue to actually understand what the lambda contains.
Your error is telling you in a somewhat odd way that the compiler is not currently capable of figuring out what the functional interface is that this lambda is implementing. Therefore, it does not know what the type of position is, therefore, the call groupModelList.get(position) does not work; int is required, but the type of position is 'I do not know yet; I cannot know until I know what functional interface this lambda is trying to implementation and for some reason I can't know that right now'. Which isn't int, so you get that error.
one trivial fix is to be explicit. Make that (int position) -> { ... } instead. This may then lead you to the real error you're interested in. For example, if you haven't imported GroupAdapter, this would happen.
Ok, this might be a stupid question. However, it really confuses me;
What is the difference between a method like :
toString()
and a method like
toString(String s) ?
I know the last one doesn't exist but let's say i made one like this.
Why should I choose to make a method that can be invoked like this: object.method(); and not: method(object j ); i hope i could explain myself.
It all depends on what you want the method to do.
For instance, the .toString(), is used to provide a string representation of the object. In this case, all the data which the method requires to operate as expected is stored within the object itself, thus, no external input is required.
Taking a different example, printToStream(Stream stream) (where Stream would be some interface used by all the streams, be it file streams, console streams, network streams, etc). In this case, the method needs to know to which stream it must write to.
The class to which the printToStream method belongs could have a property which denotes to which stream it must print, and thus allowing us to change the signature of printToStream to printToStream(), but that would require 2 lines of code to set up, and in this case, this can potentially introduce problems, especially if you need to print to different streams and at some point, you forget to set the property. Thus, in this case, having the method take in the extra parameter results in cleaner code which is less error prone.
EDIT: The parseInt method is a static method which is provided by the Integer class which is used to transform items from one type to integer. Static methods are methods which need to be self contained, so if you want to transform one object from one form to another using a static method, passing it as a parameter is the way to go.
The suggestion you are making would take the look of something like so: int a = "123".ToInteger();. I guess that that would be one way to go around doing the same thing, but in the end the Java specification was not designed with that frame of mind.
EDIT 2: I'll try and expand my answer the one provided by # user3284549. Please note that my answer is in no means final and should be supplimented by other material you can find online. In Java, methods are either:
Static. Static methods are methods which have no state (more on that later) and are self contained. As seen earlier, the .parseInt method from the Integer class is one example of such method. Another examples are provided by the Math class.
Non Static. Non static methods are methods which are made available once that an object is initialized (or instantiated). These methods are methods which act upon the state of the object, or else, expose some functionality which the object provides which might, in turn, affect how it behaves.
Taking your dice example, again, you can achieve this in two ways:
Let us assume that we have a class called Dice:
public class Dice {
private int value;
public int getValue() {
return this.value;
}
public void setValue(int value) {
this.value = value;
}
}
Static method
public static void roll(Dice d) {
//Rolling the dice entails a potential change in it's current value. Thus, you would need to access the dice itself and update the value.
Random r = ...
d.setValue(randomNumber);
}
Non Static Method
We just enhance the Dice class to have a new method which mimics a dice roll as follows:
public void roll() {
Random r = ...;
this.value = randomNumber;
}
If you notice, even in the static method, we still made use of a method which takes in a parameter. The particular setXXX methods (and their counter parts getXXX methods provide us with encapsulation). This is because we need to change the state of the Dice object.
Lets proceed with you example -
object.method();
object.method(Object j);
The first one does some operations on it's variable and returns/set some value (although there may be a lot of other cases, but for simplicity just consider these). When the method is toString() it actually represents a string representation of some important properties of the Object. In this case the toString() method don't need to be feed some argument from the outside of the object.
And when you use object.method(Object j) it means you need to provide some arguments to complete it's task.
For the second part of your question. Think about encapsulation. If the method needs access to data that is private to the object then object.method() would be the correct way. And also it is probably not going to be helpful in processing objects of any other type.
For the second type, it could be a static method or utility method commonly used on many different objects. The method implementation logic doesn't have to be tightly related to the object's internal implementation.
I have a function
boolean isValid(/* what goes in here? */) {
//do stuff
}
In the function signature, what do I have to enter in the parameter list in order for the method to accept a single parameter that may be of any type (primitive or object)?
I have searched around on this site and google, but I could only find situations where the return type is unknown.
If you have the function accept the generic object type, Java will create an object version of any primitive data type (i.e. Integer for int).
Reading the question and the comments, it seems like your perception of how compiled languages work may be a bit off.
If you make your function accept only one type (e.g. String), then it will fail to compile if the caller does not pass an object that is an instance of that type. "Not compiling" means they will not even be able to run the program without fixing the error. The compiler enforces this type safety for you, so you don't have to worry about this.
After reading through the comments it seems like you have a business need to valid any object people pass to you, and possibly, you will have to support more types as time goes on.
The simplest solution is like what jtoomey said, make a method like public boolean isValid(Object val). However, think about how much if statements you have to write, and how hard is it to modify the code when new type validation are needed.
To me, I would probably do something bit more complicated than just providing a single method. I would leverage factory to create validator base on class type like:
public interface Validator<T> {
public boolean isValid(T val) {
}
}
public class ValidatorFactory {
public static ValidatorFactory create(String configFile) {
/*read config and create new instance */
}
public Validator<T> createValidator(Class<T> clazz) {
/* base on config and create validator base on type*/
}
}
public class Application {
public static ValidatorFactory vFactory = ValidatorFactory.create()
public static void main(String[] args) {
Object val = Arguments.getVal(); //assume this exists
Validator<Object> validator = vFactory.create(val.class);
if (validator == null) {
System.out.println("not valid");
return;
}
System.out.println(validator.isValid());
}
}
Note that personally I feel this is a terrible solution, because you are throwing away the type safe feature of Java. But if you really must, having a configurable factory would be better than just a method that takes in any type. Having the Validator interface allows you to know the type when you are writing validation code.
I think you are a bit confused.
I will try to clarify some things:
You probably know that the return type of a method is the value that will be pass to the part of the code that called that method(aka know as client). Every method/function in Java can only return only one type(I assume you are familiar with basic polymorphism and you know what an IS A relationships is...). Here is the first clarification, you can return only one type, but one or many objects(There are data structure types).
Arguments are the values that the caller/client of the method/function can pass into the it for processing. Arguments can have zero or many parameters, this mean that you can pass as many objects as you want.
Parameters are exactly the same as arguments it is just a terminology difference nothing else. I you want to be accurate with the terms, you can say that parameters are the brackets when you define the method and argument are those brackets when you call the method.
In either the return type or in the parameters/arguments, the 2 types of types you can pass are Objects or primitive types.
If you use something of type Object, this will allow you to return any object(Object is the super class of all classes). But primitive types are not objects, so a type Object in a signature will not allow you to pass a number, but there is one little trick...
In Java there are special types of Objects known as primitive wrappers(Integer,Double...) this objects are object representations of primitives, sometimes they are used because they have some inbuilt functions that help programmers to easily manipulate the data(That is not the main point, keep reading...),every wrapper that represents a numerical primitive type, extends a class called Number and because of one feature that Java have known as autoboxing, you can pass primitives into Wrappers automatically.
Anyway, I don't know if this is the trick you were looking for, but in any case I want just to advice you, that there is no reason at all to do what you are trying, It sounds really strange and I don't think that such thing is really needed in real life programming.
Have a look at this code :
public static void main( String[] args )
{
App app = new App();
app.method(5);
}
public void method(Number number) {
System.out.print(number);
}
Another alternative:
Another example that I can think about in order to make a parameter universal is by the use of generics. So just for ending this answer to prove my point, here a method that will allow you pass anything you want, no mater if is primitive or object:
public class App
{
public static void main( String[] args )
{
App app = new App();
app.method(5);
app.someMethod(9);
app.someMethod("Whatever");
app.someMethod(true);
}
public void method(Number number) {
System.out.println(number);
}
public <T> void someMethod(T t) {
System.out.println(t);
}
}
I hope you find this useful, but I insist that I doubt that you will never do something like this in real life.
I'm currently brushing up my Java and reading up on Generics. Since they were not treated extensively in my Java class, I'm still having some trouble wrapping my mind about it, so please keep that in mind when answering.
First of all, I'm pretty sure that what I'm trying to is not possible. However, I'd like to find out where my thinking is wrong and how I should go about achieving what I want.
What I'm trying to do is manipulating an object that implements a generic interface from another class that has no knowledge about the instantiated type. Thus, I have something like the following classes:
public interface CalledInterface<E> {
public E get() { ... }
public set(E e) { ... }
}
public class Called implements CalledInterface<String> {
...
}
Now what I want to do is:
public class Caller {
protected CalledInterface<?> c;
public Caller (CalledInterface<?> arg) {
c = arg;
}
public void run(){
// I can do this:
c.set(c.get());
// But I'd want to be able to do something like:
<?> element = c.get();
c.set(element);
}
}
What is the fundamental flaw in my thinking, if there is one? And what approach should I rather be taking?
First of all, keep in mind that generics is a compile time thing not a runtime.
Now in your Caller you defined Called c. Called is defined to implement CalledInterface<String>, so automatically, Called has the following methods generated at compile time:
String get();
void set(String e); //i assume you wanted to return void
So essentially this doesn't really make sense:
<?> element = c.get();
The Caller class isn't even aware Called is using generics internally, for it, Called just deals with strings.
UPDATE
Based on your comment, since you don't want Caller to use Called directly but use CalledInterface first thing you have to do is change the type of c to that. In this case you should not use generics, because the whole point of generics is that the same class is used in different scenarios with different types (again determined at compile time), enforcing types without having repeated code.
If I understand correctly you don't want to restrict Caller to use String, so what you have to do is change CalledInterface to not use generics, and change the methods to:
Object get();
void set(Object o);
This is how we used to do things before Generics in Java 1.4. You obviously run the risk of not having type safety, so think through whether what you want really makes design sense, because it probably does not because you have to do instanceof anyway to check the type to use the Object in a useful way (i.e. to access its methods).
If on the other hand you just change the c member (and the constructor argument of Caller) to:
CalledInterface<String> c;
Your Caller will be interacting with the CalledInterface rather than the implementation and at the same time still be type safe. So you can still pass an instance of Called and set it to c.
After your edit:
// I can do this:
c.set(c.get());
No you can't. It won't compile with c being CalledInterface<?>. (Have you even tried it?)
To do this, you can use a "capture helper":
private static <T> void helper(CalledInterface<T> c) {
c.set(c.get());
}
public void run(){
helper(c);
}
Which also solves your second problem:
private static <T> void helper(CalledInterface<T> c) {
T element = c.get();
c.set(element);
}
public void run(){
helper(c);
}
There are a few minor mistakes in your code:
protected Called c;
public Caller (CalledInterface arg) {
c = arg;
}
You are not allowed to assign arg here, because the type CalledInterface is not a subtype of Called (it is the other way around)
Also you should give type information when using CalledInterface (it is allowed to leave it out, but only for legacy purposes).
Now to the part you are wondering about. For the type Called, the compiler knows get() returns a String, if you are not interested in that, you can of course always use Object as the type of element. The compiler also knows that set() takes a String as argument, so it requires you to give one. In generics is essentially the same as using Object in a case without generics (even though it isn't allowed on the location you use it, because it doesn't make sense). This means that you would be telling the compiler to forget the type on the first line (calling get()) and to unforget it on the line below.
In a constructor in Java, if you want to call another constructor (or a super constructor), it has to be the first line in the constructor. I assume this is because you shouldn't be allowed to modify any instance variables before the other constructor runs. But why can't you have statements before the constructor delegation, in order to compute the complex value to the other function? I can't think of any good reason, and I have hit some real cases where I have written some ugly code to get around this limitation.
So I'm just wondering:
Is there a good reason for this limitation?
Are there any plans to allow this in future Java releases? (Or has Sun definitively said this is not going to happen?)
For an example of what I'm talking about, consider some code I wrote which I gave in this StackOverflow answer. In that code, I have a BigFraction class, which has a BigInteger numerator and a BigInteger denominator. The "canonical" constructor is the BigFraction(BigInteger numerator, BigInteger denominator) form. For all the other constructors, I just convert the input parameters to BigIntegers, and call the "canonical" constructor, because I don't want to duplicate all the work.
In some cases this is easy; for example, the constructor that takes two longs is trivial:
public BigFraction(long numerator, long denominator)
{
this(BigInteger.valueOf(numerator), BigInteger.valueOf(denominator));
}
But in other cases, it is more difficult. Consider the constructor which takes a BigDecimal:
public BigFraction(BigDecimal d)
{
this(d.scale() < 0 ? d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale())) : d.unscaledValue(),
d.scale() < 0 ? BigInteger.ONE : BigInteger.TEN.pow(d.scale()));
}
I find this pretty ugly, but it helps me avoid duplicating code. The following is what I'd like to do, but it is illegal in Java:
public BigFraction(BigDecimal d)
{
BigInteger numerator = null;
BigInteger denominator = null;
if(d.scale() < 0)
{
numerator = d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale()));
denominator = BigInteger.ONE;
}
else
{
numerator = d.unscaledValue();
denominator = BigInteger.TEN.pow(d.scale());
}
this(numerator, denominator);
}
Update
There have been good answers, but thus far, no answers have been provided that I'm completely satisfied with, but I don't care enough to start a bounty, so I'm answering my own question (mainly to get rid of that annoying "have you considered marking an accepted answer" message).
Workarounds that have been suggested are:
Static factory.
I've used the class in a lot of places, so that code would break if I suddenly got rid of the public constructors and went with valueOf() functions.
It feels like a workaround to a limitation. I wouldn't get any other benefits of a factory because this cannot be subclassed and because common values are not being cached/interned.
Private static "constructor helper" methods.
This leads to lots of code bloat.
The code gets ugly because in some cases I really need to compute both numerator and denominator at the same time, and I can't return multiple values unless I return a BigInteger[] or some kind of private inner class.
The main argument against this functionality is that the compiler would have to check that you didn't use any instance variables or methods before calling the superconstructor, because the object would be in an invalid state. I agree, but I think this would be an easier check than the one which makes sure all final instance variables are always initialized in every constructor, no matter what path through the code is taken. The other argument is that you simply can't execute code beforehand, but this is clearly false because the code to compute the parameters to the superconstructor is getting executed somewhere, so it must be allowed at a bytecode level.
Now, what I'd like to see, is some good reason why the compiler couldn't let me take this code:
public MyClass(String s) {
this(Integer.parseInt(s));
}
public MyClass(int i) {
this.i = i;
}
And rewrite it like this (the bytecode would be basically identical, I'd think):
public MyClass(String s) {
int tmp = Integer.parseInt(s);
this(tmp);
}
public MyClass(int i) {
this.i = i;
}
The only real difference I see between those two examples is that the "tmp" variable's scope allows it to be accessed after calling this(tmp) in the second example. So maybe a special syntax (similar to static{} blocks for class initialization) would need to be introduced:
public MyClass(String s) {
//"init{}" is a hypothetical syntax where there is no access to instance
//variables/methods, and which must end with a call to another constructor
//(using either "this(...)" or "super(...)")
init {
int tmp = Integer.parseInt(s);
this(tmp);
}
}
public MyClass(int i) {
this.i = i;
}
I think several of the answers here are wrong because they assume encapsulation is somehow broken when calling super() after invoking some code. The fact is that the super can actually break encapsulation itself, because Java allows overriding methods in the constructor.
Consider these classes:
class A {
protected int i;
public void print() { System.out.println("Hello"); }
public A() { i = 13; print(); }
}
class B extends A {
private String msg;
public void print() { System.out.println(msg); }
public B(String msg) { super(); this.msg = msg; }
}
If you do
new B("Wubba lubba dub dub");
the message printed out is "null". That's because the constructor from A is accessing the uninitialized field from B. So frankly it seems that if someone wanted to do this:
class C extends A {
public C() {
System.out.println(i); // i not yet initialized
super();
}
}
Then that's just as much their problem as if they make class B above. In both cases the programmer has to know how the variables are accessed during construction. And given that you can call super() or this() with all kinds of expressions in the parameter list, it seems like an artificial restriction that you can't compute any expressions before calling the other constructor. Not to mention that the restriction applies to both super() and this() when presumably you know how to not break your own encapsulation when calling this().
My verdict: This feature is a bug in the compiler, perhaps originally motivated by a good reason, but in its current form it is an artifical limitation with no purpose.
I find this pretty ugly, but it helps
me avoid duplicating code. The
following is what I'd like to do, but
it is illegal in Java ...
You could also work around this limitation by using a static factory method that returns a new object:
public static BigFraction valueOf(BigDecimal d)
{
// computate numerator and denominator from d
return new BigFraction(numerator, denominator);
}
Alternatively, you could cheat by calling a private static method to do the computations for your constructor:
public BigFraction(BigDecimal d)
{
this(computeNumerator(d), computeDenominator(d));
}
private static BigInteger computeNumerator(BigDecimal d) { ... }
private static BigInteger computeDenominator(BigDecimal d) { ... }
The constructors must be called in order, from the root parent class to the most derived class. You can't execute any code beforehand in the derived constructor because before the parent constructor is called, the stack frame for the derived constructor hasn't even been allocated yet, because the derived constructor hasn't started executing. Admittedly, the syntax for Java doesn't make this fact clear.
Edit: To summarize, when a derived class constructor is "executing" before the this() call, the following points apply.
Member variables can't be touched, because they are invalid before base
classes are constructed.
Arguments are read-only, because the stack frame has not been allocated.
Local variables cannot be accessed, because the stack frame has not been allocated.
You can gain access to arguments and local variables if you allocated the constructors' stack frames in reverse order, from derived classes to base classes, but this would require all frames to be active at the same time, wasting memory for every object construction to allow for the rare case of code that wants to touch local variables before base classes are constructed.
"My guess is that, until a constructor has been called for every level of the heierarchy, the object is in an invalid state. It is unsafe for the JVM to run anything on it until it has been completely constructed."
Actually, it is possible to construct objects in Java without calling every constructor in the hierarchy, although not with the new keyword.
For example, when Java's serialization constructs an object during deserialization, it calls the constructor of the first non-serializable class in the hierarchy. So when java.util.HashMap is deserialized, first a java.util.HashMap instance is allocated and then the constructor of its first non-serializable superclass java.util.AbstractMap is called (which in turn calls java.lang.Object's constructor).
You can also use the Objenesis library to instantiate objects without calling the constructor.
Or if you are so inclined, you can generate the bytecode yourself (with ASM or similar). At the bytecode level, new Foo() compiles to two instructions:
NEW Foo
INVOKESPECIAL Foo.<init> ()V
If you want to avoid calling the constructor of Foo, you can change the second command, for example:
NEW Foo
INVOKESPECIAL java/lang/Object.<init> ()V
But even then, the constructor of Foo must contain a call to its superclass. Otherwise the JVM's class loader will throw an exception when loading the class, complaining that there is no call to super().
Allowing code to not call the super constructor first breaks encapsulation - the idea that you can write code and be able to prove that no matter what someone else does - extend it, invoke it, instansiate it - it will always be in a valid state.
IOW: it's not a JVM requirement as such, but a Comp Sci requirement. And an important one.
To solve your problem, incidentally, you make use of private static methods - they don't depend on any instance:
public BigFraction(BigDecimal d)
{
this(appropriateInitializationNumeratorFor(d),
appropriateInitializationDenominatorFor(d));
}
private static appropriateInitializationNumeratorFor(BigDecimal d)
{
if(d.scale() < 0)
{
return d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale()));
}
else
{
return d.unscaledValue();
}
}
If you don't like having separate methods (a lot of common logic you only want to execute once, for instance), have one method that returns a private little static inner class which is used to invoke a private constructor.
My guess is that, until a constructor has been called for every level of the heierarchy, the object is in an invalid state. It is unsafe for the JVM to run anything on it until it has been completely constructed.
Well, the problem is java cannot detect what 'statements' you are going to put before the super call. For example, you could refer to member variables which are not yet initialized. So I don't think java will ever support this.
Now, there are many ways to work around this problem such as by using factory or template methods.
Look it this way.
Let's say that an object is composed of 10 parts.
1,2,3,4,5,6,7,8,9,10
Ok?
From 1 to 9 are in the super class, part #10 is your addition.
Simple cannot add the 10th part until the previous 9 are completed.
That's it.
If from 1-6 are from another super class that fine, the thing is one single object is created in a specific sequence, that's the way is was designed.
Of course real reason is far more complex than this, but I think this would pretty much answers the question.
As for the alternatives, I think there are plenty already posted here.