Could somebody explain this function I've accidentally written ("Any" keyword)?

Cyber_Agent :

I have been writing a small java application which uses Serialization/Deserialization to save/load ArrayLists. I had written the following function which takes a file path and deserializes the objects within it:

private Object deserialize(String fileName)
            throws IOException, ClassNotFoundException {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName))) {
            return ois.readObject();
        }
}

Since this function returns an Object type, I would then have to cast it to an ArrayList like this:

ArrayList<String> arrayList = (ArrayList<String>)deserialize("test.file");

(The line above would have to be surrounded by a try/catch statement, but I did not include it here for the sake of readability)

That process worked fine for me, however I wanted to try and see if I could edit the code to a point where I wouldn't have to cast the object myself, and so I, quite jokingly, typed Any as the return type of my function, and the compiler didn't complain. I then changed my function to the following, and to my surprise it actually worked!

private <Any> Any deserialize(String fileName)
            throws IOException, ClassNotFoundException {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName))) {
            return (Any)ois.readObject();
        }
}

When using this function, I no longer need to cast it's return value to an ArrayList, and can instead simply use:

ArrayList<String> arrayList = deserialize("test.file");

A part of me wants to just roll with this whole thing and just use the function without questioning how it works, but I know I'll have trouble doing this.

Could somebody please explain why this function works the way it does, or paraphrase just explain the Any keyword, as I have honestly never seen it before.

Mureinik :

Any isn't a keyword in Java. The key thing to notice here is the <Any> after the access modifier. This is the method's generic specification - the method is generalized with a type parameter called Any (which you then use for casting in the method body), and when you call the method, Java will infer the return type.

But there's nothing special about the word "Any". You could have used "T" or "SomeType" or even "SpongeBob" to the same effect.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127962&siteId=1