protected static ArrayList<Byte> getBytes(Object file){
Scanner scan;
ArrayList<Byte> bytes = new ArrayList<Byte>();
try{
/*this is what i mean i know this wont work but im trying to show what i mean :P/>
I want to cast the Object so that file is either a string or a File
*/
scan = new Scanner((file.getClass())file);
scan.useDelimiter("\\n");
while (scan.hasNext()) {
String tmp = scan.next();
for(int i = 0; i < tmp.length(); i++){
bytes.add((byte)tmp.charAt(i));
}
}
scan.close();
}catch(Exception e){System.out.println("Exception " + e);}
return bytes;
}
Generic Casting Question
Page 1 of 110 Replies - 213 Views - Last Post: 12 October 2012 - 01:14 PM
#1
Generic Casting Question
Posted 12 October 2012 - 07:46 AM
Replies To: Generic Casting Question
#2
Re: Generic Casting Question
Posted 12 October 2012 - 07:52 AM
if(file instanceof File) cast to file
else if(file instanceof String) cast to string
else throw new IllegalArgumentException
#3
Re: Generic Casting Question
Posted 12 October 2012 - 08:00 AM
The way I would structure this is by using a private method that takes the "Scanner" object and does the actual work, and 2 overloaded methods that create the scanner method based on the argument passed in.
private ArrayList<Byte> getBytesInternal(Scanner scn) { ... }
public ArrayList<Byte> getBytes(File f) { return getBytesInternal(new Scanner(f)); }
public ArrayList<Byte> getBytes(String s) { return getBytesInternal(new Scanner(s)); }
#4
Re: Generic Casting Question
Posted 12 October 2012 - 08:10 AM
#5
Re: Generic Casting Question
Posted 12 October 2012 - 08:40 AM
#6
Re: Generic Casting Question
Posted 12 October 2012 - 09:38 AM
Quote
Can you imagine the API for that?
This post has been edited by blackcompe: 12 October 2012 - 09:38 AM
#7
Re: Generic Casting Question
Posted 12 October 2012 - 10:01 AM
- Generics are not made for type checking - if all the different types had a shared interface or parent class, you might have been able to pass that in or use a Bound generic type
- You can pass an Object and check the type inside the method, but whoever is calling the method will hate you forever when they start getting exceptions
- You can overloaded methods
#8
Re: Generic Casting Question
Posted 12 October 2012 - 10:17 AM
#9
Re: Generic Casting Question
Posted 12 October 2012 - 10:20 AM
Quote
Generics are made for type checking.
This post has been edited by blackcompe: 12 October 2012 - 10:20 AM
#10
#11
Re: Generic Casting Question
Posted 12 October 2012 - 01:14 PM
|
|

New Topic/Question
Reply




MultiQuote




|