Having trouble with creating objects from instances created with ClassLoade

Hi.
I'm having a bit of trouble with casting an instance of an object from a custom ClassLoader. Don't worry - the code isn't for anything sinister - it's for one of those life simulation thingies, but I want to make it modular so people can write their own 'viruses' which compete for survival. You know the score.
Anyway. I've got the beginnings of my main class, which seems to load the class data for all 'virus' classes in a folder called 'strains'. There is a abstract class called AbstractVirus which declares the method calls for how the viruses should behave and to get textual descriptions, etc. AbstractVirus is to be subclassed to create working virus classes and these are what my main class is trying to load instances of.
Unfortuantely, I can't cast the instances into AbstractVirus objects. The error I've been getting is 'ClassCastException' which I presume is something to do with the fact that my ClassLoader and the Bootstrap ClassLoader aren't seeing eye-to-eye with the class types. Can anyone help? This line of programming is really new to me.
My code for the main class is below:
/* LifeSim.java */
public class LifeSim {
  public LifeSim() {
    /* Get a list of all classes in the 'strains' directory and store non-
     * abstract classes in an array. */
    Class virusClasses[] = null;
    try {
      /* Get a reference to the file folder 'strains' and make sure I can read
       * from it. */
      java.io.File modulesFolder = new java.io.File("strains");
      if (!modulesFolder.isDirectory() || !modulesFolder.canRead()) {
     System.out.println("Failed to find accessible 'strains' folder");
     System.exit(-1);
      /* Get a list of all the class files in the folder. */
      String virusFiles[] = modulesFolder.list(new ClassFileFilter());
      if (virusFiles.length == 0) {
     System.out.println("No virus strains in 'strains' folder");
     System.exit(-1);
      /* Create an array of class objects to store my Virus classes. Ignore the
       * abstract class as I cannot instantiate objects directly from it.*/
      virusClasses = new Class[virusFiles.length];
      VirusClassLoader classLoader = new VirusClassLoader();
      int j = 0;
      for (int i = 0; i < virusFiles.length; i++) {
     String virusName = "strains/" + virusFiles;
     Class tempClass = classLoader.loadClass(virusName);
     if (tempClass.getName().compareToIgnoreCase("strains.AbstractVirus") != 0) {
     virusClasses[j++] = tempClass;
} catch (ClassNotFoundException ncfe) {
System.out.println("Failed to access virus class files.");
ncfe.printStackTrace();
System.exit(-1);
/* TEST CODE: Create an instance of the first virus and print its class
* name and print details taken from methods defined in the AbstractVirus
* class. */
if (virusClasses.length > 0) {
try {
     // Print the class name
     System.out.println(virusClasses[0].getName());
     Object o = virusClasses[0].newInstance();
     strains.AbstractVirus av = (strains.AbstractVirus) o;
     // Print the virus name and it's description
     System.out.println(av.getQualifiedName());
     System.out.println(av.getDescription());
} catch (InstantiationException ie) { ie.printStackTrace(); }
     catch (IllegalAccessException iae) { iae.printStackTrace(); }
public static void main(String args[]) {
new LifeSim();
class ClassFileFilter implements java.io.FilenameFilter {
public boolean accept(java.io.File fileFolder, String fileName) {
if (_fileName.indexOf(".class") > 0) return true;
return false;
class VirusClassLoader extends ClassLoader {
private String legalClassName = null;
public VirusClassLoader() {
super(VirusClassLoader.class.getClassLoader());
public byte[] findClassData(String filename) {
try {
java.io.File sourcefile = new java.io.File(filename);
legalClassName = "strains." + sourcefile.getName().substring(0,sourcefile.getName().indexOf("."));
java.io.FileInputStream fis = new java.io.FileInputStream(sourcefile);
byte classbytes[] = new byte[fis.available()];
fis.read(classbytes);
fis.close();
return classbytes;
} catch (java.io.IOException ioex) {
return null;
public Class findClass(String classname) throws ClassNotFoundException {
byte classbytes[] = findClassData(classname);
if (classbytes == null) throw new ClassNotFoundException();
else {
return defineClass(legalClassName, classbytes, 0, classbytes.length);
Thank you in advance
Morgan

Two things:
I think your custom ClassLoader isn't delegating. In general a ClassLoader should begin by asking it's parent ClassLoader to get a class, and only if the parent loader fails get it itself. AFAIKS you could do what you're trying to do more easilly with URLClassLoader.
Second, beware that a java source file can, and often does, generate more than one class file. Ignore any class files whose names contain a $ character. It's possible you are loading an internal class which doesn't extend your abstract class.

Similar Messages

  • I am currently having trouble with an attached PDF fill-able form created in Acrobat being non savable in Reader

    Hello, I was wondering if you would be able to help me out?
    I am having trouble with my attached PDF fill-able form, I am creating a form that has a limit of one page so in order for more room in a certain field I have added a Hyperlink to an additional fill-able(secondary) form within the Parent document (primary fill-able form. The secondary form is inserted as an attachment into the Primary form. My problem is when I open this document up in Adobe Reader, the Primary fill-able form is savable but the attached Secondary form for which the hyperlink leads to is non-savable and is a must print only. Is there a way to make the Secondary form savable as well within the same document? or is there another way I could execute what it is I am trying to achieve?
    Trying to save other as extended reader has not worked, also if I save the attachment file as an extended reader first I am unable to attach a return hyperlink back to the Parent document,
    Help would be greatly appreciated please and thank you!

    I can't say for certain without looking at the actual PDF but it does appear that they created one large text box over multiple lines. For a fillable form it may have been smarter to remove the lines and create a box with smaller text that supports multiple lines.
    At any rate, nothing you can do about it with the free Reader (and depending on the security, maybe nothing with Acrobat either.)

  • I'm having trouble with custom ringtones.  I have downloaded the free software "makeTones" and have created some ringtones.  I then copied those to Mac and played them in ITunes.  My Itunes does not have a ringtone tab.  I can not sync the ringtones.

    I'm having trouble with custom ringtones.  I have downloaded the free software "makeTones" and have created some ringtones.  I then copied those to Mac and played them in ITunes.  My Itunes library does not have a ringtones tab.  I can not sync the ringtones (or I don't know how)!  Please help.

    Yes, the file extension is M4R.  Does it matter where I save these files on my Macbook?  I then opened them in Itunes and played them.  I did find the Tones folder in Itunes but the Tones or Ringtones tab does not show up when I select Iphone (within Itunes).  When I open the Tones folder in the Library, it is empty.  Thanks in advance for your help.

  • HT1550 I'm having trouble with importing them into iTunes and converting them at the same time. when i hold down option over the files i can't find where its supposed to say create new version. is this if you're in iTunes?

    I'm having trouble with importing them into iTunes and converting them at the same time. when i hold down option over the files i can't find where its supposed to say create new version. is this if you're in iTunes?

    You can't do it in one step. Add to iTunes first, Once the tracks are in iTunes you may convert to a different format.
    tt2

  • E-Mailing Photos from iPhoto - Having trouble with resolution

    I am having trouble with emailing pictures from i-photo. When I email pictures as attachments they end up being low resolution versions and the receiver can not print them. I can not figure out what sort of setting I must have set. Please help.

    MMVP
    Welcome to the Apple user assistance forums
    1 - how are you selecting and attaching the photos?
    2 - what is the resolution of the photos in iPhoto?
    3 - if you are using the iPhoto e-mail capability (recommended) you select a photo(s) and click mail - there you can choose actual, large, medium or small
    4 - this creates an e-mail message in the e-mail client of your choice (iPhoto preferences) - if you are using Apple mail in the lower right hand corner under the e-mail there is a menu where you can set Actual, large, medium or small
    Be sure that both selections are set the way you want them - if either is se tto small you will send a small (low resolutin) photo
    LN

  • I am having trouble with my Mac Mini's ethernet connection.   Defining a new network interface shows no ethernet adaptor.  Reloading SL from DVD repaired.  But SL update lost ethernet again.  Will Lion Fix?

    I am having trouble with my mac mini ethernet.  It had been working for weeks after an update to SL 10.6.8.
    Once it went out and i repaired it by defining a new connection from System Preferences ->Network->(left panel service, +).
    But yesterday, after a power up.  my ethernet was not working again. I tried this old trick to repair it, but the interface choices
    listed for '+' a new service did not include Ethernet any more.  And the Utilities->System Profiler->Ethernet Cards shows
    no ethernet available.
    As a last ditch effort i reloaded my original SL from DVD.  (I think it was version 10.6.4 but i could be mistaken on the version).
    The ethernet worked!  But KeyNote wasn't going to work because apparently the version i purchased depends on 10.6.8.
    So I upgraded again to SL 10.6.8 (Plus some other updates like AirPort which i don't use).
    Now the Ethernet is not working again.  I see the same symptoms as before with the Ethernet seeming not installed.
    Is this a problem seen by others?
    Would going to Lion fix the problem?
    Could AirPort actually be the culprit and not SL?
    If i stay with my original SL, would i need to repurchase a version of KeyNote for the older version of SL?

    Have you reset the SMC?
    Shut down the computer.
    Unplug the computer's power cord.
    Wait fifteen seconds.
    Attach the computer's power cord.
    Wait five seconds, then press the power button to turn on the computer.
    While you're at it, resetting the PRAM won't hurt anything and 'might' help is SMC reset didn't work (PRAM does some port control):
    Shut down the computer.
    Locate the following keys on the keyboard: Command, Option, P, and R. You will need to hold these keys down simultaneously in step 4.
    Turn on the computer.
    Press and hold the Command-Option-P-R keys. You must press this key combination before the gray screen appears.
    Hold the keys down until the computer restarts and you hear the startup sound for the second time.
    Release the keys.
    Something else you might try .... you don't say how you're updating to 10.6.8, however, if you're using Software Update, you might try downloading the 10.6.8 combo update, which contains all updates to 10.6. Sometimes, Software Update doesn't work quite right, and installing the combo update fixes that. Download the update from Apple's download site at http://support.apple.com/downloads/ , using Disk Utility repair permissions, apply the combo update, then repair permissions again.

  • Having trouble with the File and Folder Objects (PSCS3 javascript on Win)

    I'm having trouble successfully creating a new folder on my windows platform, using javascripts in photoshop. In ExtendScript Toolkit 2, set to Adobe Photoshop CS3, I've tried:
    var myFolder = new Folder("/c/Documents and Settings/vcastelo/My Documents");
    myFolder.create();
    and
    var myFolder = new Folder("/c/Documents and Settings/vcastelo/My Documents");
    is this right? what am I doing wrong? It's pretty basic stuff, I know but I can't figure is out... any help would be greatly appreciated.

    [email protected] wrote:
    > oh I see, I just figured it out... the drive designation isn't case sensitive... but i didn't add the name of new folder to the destination path.
    Yep.
    >
    > var myFolder = new Folder("c:/Documents and Settings/vcastelo/My Documents/data");
    > myFolder.create();
    The "/c/Documents and Settings/vcastelo/My Documents/data" form works, too, and
    should be preferred.
    Here's an extreme example as to why this is a good idea:
    I work in an XP/cygwin environment, so I added links to all of my drives in my
    root cygwin folder. As a result, the path /p/Pictures/2008-05-05 is the same on
    the bash command line (and other tools) as it is in PSJS. I carried this over to
    my Mac, as well. I mount P: drive in OSX then setup links so that
    /p/Pictures/2008-05-05 is also the same on the Mac. This has vastly simplified
    my work. The only time I use system-specific pathnames is in a script's UI.
    -X
    for photoshop scripting solutions of all sorts
    contact: [email protected]

  • I'm having trouble with video imported from my camera memory card.

    I'm having trouble with video imported from my camera memory card.The video breaks up and pixelizes when it's directly imported from the memory card. That makes the video useless. Why does this happen? It doesn't do that in any other video editing software. Thanks for the help.

    More info please:
    Type of camera?
    Was the card formatted in the camera doing the shooting?
    Type of files the camera is set to record?
    Al

  • I am having trouble with hdmi from MacBook to TV

    Having trouble with the sounds when I connect  hdmi from MacBook to TV

    This is the iPad forum. Do you have a question about iPad? If not, I'll ask that your post be reassigned.
    BTW, you will need to provide more detail than that for someone to help. How are you connecting the two? What have you already done to troubleshoot? What was the result?

  • I am having trouble with my bluetooth skipping while its playing music from my Itunes music...I thought that this was an antiquated problem with the new technology?

    I am having trouble with the music from my bluetooth "skipping" on my IPhone 5.  I thought that this was an antiquated problem with the new technology.  It's very frustrating to purchase all of this music and expect great sound and playability and get "skipping".  Any ideas on how to resolve this issue?

    Does the issue occur when listening to the media using the speaker or wired headphones?  If it does, the issue is with the media itself.
    If it does not, it's likely a bad connection or interference.

  • I have a Lucid 2 LG.  I have been having trouble with insuffient storage.  I have a 8G phone and have spent hours with Tier 2 tech trying to move info from the internal storage to the SD card with no luck,  When I go to storage in the settings it states t

    I have a Lucid 2 LG.  I have been having trouble with insuffient storage.  I have a 8G phone and have spent hours with Tier 2 tech trying to move info from the internal storage to the SD card with no luck,  When I go to storage in the settings it states that over 4 gigs is for Misc?  System data takes up over 4 gigs.  No one can tell me what system data consist of.  So My question is does anyone know what system data is?  I am assuming I have a 8 gigphone but can only use 4 gigs???

    System data is the OS or operating system.  That is where the recovery stays separated from the rest of the storage so that it doesn't get corrupted.  It is not accessible and non-movable.

  • Switched from a PC to a MBP, having trouble with iTunes syncing iPhones, iPods. Devices are still linked to the PC ?

    Switched from a PC to a MBP, having trouble with iTunes syncing iPhones, iPods. Devices are still linked to the PC. How do I undo the PC link without a restore / reformat?

    Post in the iTunes forum:
    https://discussions.apple.com/community/itunes
    Read:
    http://www.apple.com/support/switch101/
    http://www.macworld.com/article/1153952/superguide_switchingtoamac.html

  • Having trouble with my  email from google

    Having trouble with my email from gmail, both on my iPhone and on my iMac. It keeps asking to validate my password and e en after that it won't work. Does anyone know what to do?

    Hey Florian Fangohr,
    Thanks for the question. I understand you are experiencing issues with Mail in OS X Mavericks. Base on the symptoms you provided, the following article may help to resolve your issue:
    Mail (Mountain Lion): If your password is not saved
    http://support.apple.com/kb/PH11775
    If you click “Save password” in a dialog in Mail but still have to enter your password, there are a couple of things you can try.
    - Open Keychain Access, and then locate and delete the mail account password item.
    While in Keychain Access, you can also choose Keychain Access > Keychain First Aid to verify and repair keychain settings.
    - Open Disk Utility, and then select the volume (for your hard disk or disks) in the list of disks and volumes. Click First Aid and then click Verify Disk. If necessary, click Repair Disk. Then send yourself a test message.
    Note: The same steps apply for OS X Mavericks
    Thanks,
    Matt M.

  • Anyone else having trouble with their iPad disconnecting from wifi since 6.0.1 update

    Anyone else having trouble with their iPad dropping wifi about once a week since 6.0.1 update?

    Some things to try first:
    1. Turn Off your iPad. Then turn Off (disconnect power cord for 30 seconds or longer) the wireless router & then back On. Now boot your iPad. Hopefully it will see the WiFi.
    2. Go to Settings>Wi-Fi and turn Off. Then while at Settings>Wi-Fi, turn back On and chose a Network.
    3. Change the channel on your wireless router (Auto or Channel 6 is best). Instructions at http://macintoshhowto.com/advanced/how-to-get-a-good-range-on-your-wireless-netw ork.html
    4. Go into your router security settings and change from WEP to WPA with AES.
    5.  Renew IP Address: (especially if you are droping internet connection)
        •    Launch Settings app
        •    Tap on Wi-Fi
        •    Tap on the blue arrow of the Wi-Fi network that you connect to from the list
        •    In the window that opens, tap on the Renew Lease button
    ~~~~~~~~~~~~~~~~~~~~~~~~~
    iOS 6 Wifi Problems/Fixes
    Fix For iOS 6 WiFi Problems?
    http://tabletcrunch.com/2012/09/27/fix-ios-6-wifi-problems/
    Did iOS 6 Screw Your Wi-Fi? Here’s How to Fix It
    http://gizmodo.com/5944761/does-ios-6-have-a-wi+fi-bug
    How To Fix Wi-Fi Connectivity Issue After Upgrading To iOS 6
    http://www.iphonehacks.com/2012/09/fix-wi-fi-connectivity-issue-after-upgrading- to-ios-6.html
    iOS 6 iPad 3 wi-fi "connection fix" for netgear router
    http://www.youtube.com/watch?v=XsWS4ha-dn0
    Apple's iOS 6 Wi-Fi problems
    http://www.zdnet.com/apples-ios-6-wi-fi-problems-linger-on-7000004799/
    ~~~~~~~~~~~~~~~~~~~~~~~
    Look at iOS Troubleshooting Wi-Fi networks and connections  http://support.apple.com/kb/TS1398
    iPad: Issues connecting to Wi-Fi networks  http://support.apple.com/kb/ts3304
    WiFi Connecting/Troubleshooting http://www.apple.com/support/ipad/wifi/
    How to Fix: My iPad Won't Connect to WiFi
    http://ipad.about.com/od/iPad_Troubleshooting/ss/How-To-Fix-My-Ipad-Wont-Connect -To-Wi-Fi.htm
    iOS: Connecting to the Internet http://support.apple.com/kb/HT1695
    iOS: Recommended settings for Wi-Fi routers and access points  http://support.apple.com/kb/HT4199
    How to Quickly Fix iPad 3 Wi-Fi Reception Problems
    http://osxdaily.com/2012/03/21/fix-new-ipad-3-wi-fi-reception-problems/
    iPad Wi-Fi Problems: Comprehensive List of Fixes
    http://appletoolbox.com/2010/04/ipad-wi-fi-problems-comprehensive-list-of-fixes/
    Fix iPad Wifi Connection and Signal Issues  http://www.youtube.com/watch?v=uwWtIG5jUxE
    Fix Slow WiFi Issue https://discussions.apple.com/thread/2398063?start=60&tstart=0
    How To Fix iPhone, iPad, iPod Touch Wi-Fi Connectivity Issue http://tinyurl.com/7nvxbmz
    Unable to Connect After iOS Update - saw this solution on another post.
    https://discussions.apple.com/thread/4010130
    Note - When troubleshooting wifi connection problems, don't hold your iPad by hand. There have been a few reports that holding the iPad by hand, seems to attenuate the wifi signal.
    ~~~~~~~~~~~~~~~
    If any of the above solutions work, please post back what solved your problem. It will help others with the same problem.
     Cheers, Tom

  • I am having trouble with my iphoto. I can't print from there or do much of anything. When i double click on an event it doesnt open. Any suggestions?

    I am having trouble with my iphoto. I can't print from there or do much of anything. When i double click on an event it doesnt open. Any suggestions?

    ~/Library/Preferences/com.apple.iPhoto.plist
    ~ = your home folder
    Here's a picture
    Chris

  • I am having trouble with downloading videos from my Sony HDR-XR160 video camera. iMovie doesnt open up when i connect the camcorder. any suggesions?

    i am having trouble with downloading videos from my Sony HDR-XR160 video camera. iMovie doesnt open up when i connect the camcorder. any suggesions?

    Looking up your camera online, I found it is capable of 1920 x 1080 Full HD 60p Recording. It's the 60p (60 frames per second Progressive) that's the problem I think. iMovie '11 will do 60i (Interlaced). You might need to convert it from the format the camera currently uses into another format to get it into iMovie. Read more about it on this link here: How to import 60p footage From that message thread comes the recommendation to use ClipWrap to convert the camera's video clips now that they are in 60p:
    Tom Wolsky
    Re: How to import 60p footage 
    Aug 17, 2011 12:40 PM (in response to ptburnett68)
    Use ClipWrap to rewrap to QuickTime. Import the files. Edit in either 59.94 or 29.97. The latter if you want to use the high frame rate for slomo

Maybe you are looking for

  • Ipod nano is detected but not identified

    I have an ipod nano 3rd generation that works fine on my Macbook Pro laptop, but when I plug it in to my Dual 800MHz PowerPC G4, (it's an early classic stack), the computer tells me an ipod has been detected but can not identify it, and tells me to u

  • On iOS7, Korean Language Input Method with serious error.

    Korean Input Method for iOS7 has serious problems with bluetooth keyboard. It has absolutely incorrect state transition for the keyboard typings. Keyboard input and cursor moving are independently acting. On the word processing apps, when the line ch

  • Streaming iPhoto to HD-Plasma Screen

    Hi guys, I love my new iMac G5...just switched from Windows XP. I posted a question to the iDVD forum, but need more details. I would like to stream a slideshow I created in iPhoto to my plasma HDTV that is 2 rooms away. A guy in the iDVD forum sugge

  • 2 BIW connections to 1 R/3 system

    Hello, We have one R/3 system to which we want to connect 2 BIW systems. The BIW systems will be picking data from the same client in the R/3 system. when i try to configure the rfc connections, it fails since the client can have only one logical nam

  • The following adress as permanent fatal error

    While approving a email notification for iexpence approval email notification getting mail back with content as ----- The following addresses had permanent fatal errors ----- <[email protected]> (reason: 550 5.2.0 /var/mail/wf_ibisbtc: irregular file