Create Class objects from an Array of File Objects

Hi There,
I'm having extreme difficulty in trying to convert an array of file objects to Class objects. My problem is as follows: I'm using Jfilechooser to select a directory and get an array of files of which are all .class files. I want to create Class objects from these .class files. Therefore, i can extract all the constructor, method and field information. I eventually want this class information to display in a JTree. Very similar to the explorer used in Netbeans. I've already created some code below, but it seems to be throwing a NoSuchMethodError exception. Can anyone please help??
Thanks in advance,
Vikash
/* the following is the class im using */
class FileClassLoader extends ClassLoader {
private File file;
public FileClassLoader (File ff) {
this.file = ff;
protected synchronized Class loadClass() throws ClassNotFoundException {
Class c = null;
try {
// Get size of class file
int size = (int)file.length();
// Reserve space to read
byte buff[] = new byte[size];
// Get stream to read from
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream (fis);
// Read in data
dis.readFully (buff);
// close stream
dis.close();
// get class name and remove ".class"
String classname = null;
String filename = file.getName();
int i = filename.lastIndexOf('.');
if(i>0 && i<filename.length()-1) {
classname = filename.substring(0,i);
// create class object from bytes
c = defineClass (classname, buff, 0, buff.length);
resolveClass (c);
} catch (java.io.IOException e) {
e.printStackTrace();
return c;
} // end of method loadClass
} // end of class FileClassLoader
/* The above class is used in the following button action in my gui */
/* At the moment im trying to output the data to standard output */
private void SelectPackage_but2ActionPerformed(java.awt.event.ActionEvent evt) {
final JFileChooser f = new JFileChooser();
f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int rVal = f.showOpenDialog(Remedy.this);
// selects directory
File dir = f.getSelectedFile();
// gets a list of files within the directory
File[] allfiles = dir.listFiles();
// for loop to filter out all the .class files
for (int k=0; k < allfiles.length; k++) {
if (allfiles[k].getName().endsWith(".class")) {
try {
System.out.println("File name: " + allfiles[k].getName()); // used for debugging
FileClassLoader loader = new FileClassLoader(allfiles[k]);
Class cl = loader.loadClass();
//Class cl = null;
Class[] interfaces = cl.getInterfaces();
java.lang.reflect.Method[] methods = cl.getDeclaredMethods();
java.lang.reflect.Field[] fields = cl.getDeclaredFields();
System.out.println("Class Name: " + cl.getName());
//print out methods
for (int m=0; m < methods.length; m++) {
System.out.println("Method: " + methods[m].getName());
// print out fields
for (int fld=0; fld < fields.length; fld++) {
System.out.println("Field: " + fields[fld].getName());
} catch (Exception e) {
e.printStackTrace();
} // end of if loop
} // end of for loop
packageName2.setText(dir.getPath());
}

It's throwing the exeption on the line:
FileClassLoader loader = new FileClassLoader(allfiles[k]);
I'm sure its something to do with the extended class i've created. but i cant seem to figure it out..
Thanks if you can figure it out

Similar Messages

  • How can i use class reference from an array effeciently?

    Hi,
    I made some test here with getting a class reference from an array and using the reference's methods or variables.
    Basically arrayEx is a container of type Array and it contains the Person's class instance in it. Num is a number extracted from the Person's instance
    Example #1----Strongly typed
    Var reference:Person;
    Var num:int;
    //Assignation
    reference=arrayEx[0];-----IT IS SLOW HERE
    //Use
    num=reference.number --- IT IS FAST HERE
    Example #2---Not typed
    Var reference:*;
    Var num:int;
    //Assignation
    reference=arrayEx[0]; ---- IT IS FAST HERE
    //Use
    num=reference.number ---IT IS SLOW HERE
    No matter what i change in both code like casting Person on arrayEx, i cant seem to make them work both fast at the same time
    If someone knows how, please tell me,
    Dominik

    Hi,
    I made some test here with getting a class reference from an array and using the reference's methods or variables.
    Basically arrayEx is a container of type Array and it contains the Person's class instance in it. Num is a number extracted from the Person's instance
    Example #1----Strongly typed
    Var reference:Person;
    Var num:int;
    //Assignation
    reference=arrayEx[0];-----IT IS SLOW HERE
    //Use
    num=reference.number --- IT IS FAST HERE
    Example #2---Not typed
    Var reference:*;
    Var num:int;
    //Assignation
    reference=arrayEx[0]; ---- IT IS FAST HERE
    //Use
    num=reference.number ---IT IS SLOW HERE
    No matter what i change in both code like casting Person on arrayEx, i cant seem to make them work both fast at the same time
    If someone knows how, please tell me,
    Dominik

  • Creating a sound from an array of numeric values and playing it on speakers

    How do I create take a sound I have stored as an array (or could be an arraylist if needed) of numeric values (at the moment as doubles) whiten my program and output it to speakers? I am using blueJ.
    for example (0, 0.1, 0.4, 0.8, 0.9, 1, 0.8, 0.6, 0.3, 0.1, etc...) would be a very high frequency sin wave.
    Edited by: alan2here on Feb 6, 2008 11:28 AM

    I stumbled upon this thread with a question somewhat related:
    I've recorded a wave file from microphone. But what I would like is an array of numbers in the same way alan said. I'm also working on my own project involving signal processing (i'm trying to do speech recognition).
    I can't really find a nice way of getting that array of numbers. I've tried to find out how wave file stores it's data, and directly read from the File object, but i figured there should be an easier way...
    I used this code to read the sound:
    *     SimpleAudioRecorder.java
    *     This file is part of jsresources.org
    * Copyright (c) 1999 - 2003 by Matthias Pfisterer
    * All rights reserved.
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    * - Redistributions of source code must retain the above copyright notice,
    *   this list of conditions and the following disclaimer.
    * - Redistributions in binary form must reproduce the above copyright
    *   notice, this list of conditions and the following disclaimer in the
    *   documentation and/or other materials provided with the distribution.
    |<---            this code is formatted to fit into 80 columns             --->|
    import java.io.IOException;
    import java.io.File;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.TargetDataLine;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.AudioFileFormat;
    public class SimpleAudioRecorder
    extends Thread
         private TargetDataLine          m_line;
         private AudioFileFormat.Type     m_targetType;
         private AudioInputStream     m_audioInputStream;
         private File               m_outputFile;
         public SimpleAudioRecorder(TargetDataLine line,
                             AudioFileFormat.Type targetType,
                             File file)
              m_line = line;
              m_audioInputStream = new AudioInputStream(line);
              m_targetType = targetType;
              m_outputFile = file;
         /** Starts the recording.
             To accomplish this, (i) the line is started and (ii) the
             thread is started.
         public void start()
              /* Starting the TargetDataLine. It tells the line that
                 we now want to read data from it. If this method
                 isn't called, we won't
                 be able to read data from the line at all.
              m_line.start();
              /* Starting the thread. This call results in the
                 method 'run()' (see below) being called. There, the
                 data is actually read from the line.
              super.start();
         /** Stops the recording.
             Note that stopping the thread explicitely is not necessary. Once
             no more data can be read from the TargetDataLine, no more data
             be read from our AudioInputStream. And if there is no more
             data from the AudioInputStream, the method 'AudioSystem.write()'
             (called in 'run()' returns. Returning from 'AudioSystem.write()'
             is followed by returning from 'run()', and thus, the thread
             is terminated automatically.
             It's not a good idea to call this method just 'stop()'
             because stop() is a (deprecated) method of the class 'Thread'.
             And we don't want to override this method.
         public void stopRecording()
              m_line.stop();
              m_line.close();
         /** Main working method.
             You may be surprised that here, just 'AudioSystem.write()' is
             called. But internally, it works like this: AudioSystem.write()
             contains a loop that is trying to read from the passed
             AudioInputStream. Since we have a special AudioInputStream
             that gets its data from a TargetDataLine, reading from the
             AudioInputStream leads to reading from the TargetDataLine. The
             data read this way is then written to the passed File. Before
             writing of audio data starts, a header is written according
             to the desired audio file type. Reading continues untill no
             more data can be read from the AudioInputStream. In our case,
             this happens if no more data can be read from the TargetDataLine.
             This, in turn, happens if the TargetDataLine is stopped or closed
             (which implies stopping). (Also see the comment above.) Then,
             the file is closed and 'AudioSystem.write()' returns.
         public void run()
                   try
                        AudioSystem.write(
                             m_audioInputStream,
                             m_targetType,
                             m_outputFile);
                   catch (IOException e)
                        e.printStackTrace();
         public static void main(String[] args)
              if (args.length != 1 || args[0].equals("-h"))
                   printUsageAndExit();
              /* We have made shure that there is only one command line
                 argument. This is taken as the filename of the soundfile
                 to store to.
              String     strFilename = args[0];
              File     outputFile = new File(strFilename);
              /* For simplicity, the audio data format used for recording
                 is hardcoded here. We use PCM 44.1 kHz, 16 bit signed,
                 stereo.
              AudioFormat     audioFormat = new AudioFormat(
                   AudioFormat.Encoding.PCM_SIGNED,
                   44100.0F, 16, 2, 4, 44100.0F, false);
              /* Now, we are trying to get a TargetDataLine. The
                 TargetDataLine is used later to read audio data from it.
                 If requesting the line was successful, we are opening
                 it (important!).
              DataLine.Info     info = new DataLine.Info(TargetDataLine.class, audioFormat);
              TargetDataLine     targetDataLine = null;
              try
                   targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
                   targetDataLine.open(audioFormat);
              catch (LineUnavailableException e)
                   out("unable to get a recording line");
                   e.printStackTrace();
                   System.exit(1);
              /* Again for simplicity, we've hardcoded the audio file
                 type, too.
              AudioFileFormat.Type     targetType = AudioFileFormat.Type.WAVE;
              /* Now, we are creating an SimpleAudioRecorder object. It
                 contains the logic of starting and stopping the
                 recording, reading audio data from the TargetDataLine
                 and writing the data to a file.
              SimpleAudioRecorder     recorder = new SimpleAudioRecorder(
                   targetDataLine,
                   targetType,
                   outputFile);
              /* We are waiting for the user to press ENTER to
                 start the recording. (You might find it
                 inconvenient if recording starts immediately.)
              out("Press ENTER to start the recording.");
              try
                   System.in.read();
              catch (IOException e)
                   e.printStackTrace();
              /* Here, the recording is actually started.
              recorder.start();
              out("Recording...");
              /* And now, we are waiting again for the user to press ENTER,
                 this time to signal that the recording should be stopped.
              out("Press ENTER to stop the recording.");
              try
                   System.in.read();
              catch (IOException e)
                   e.printStackTrace();
              /* Here, the recording is actually stopped.
              recorder.stopRecording();
              out("Recording stopped.");
         private static void printUsageAndExit()
              out("SimpleAudioRecorder: usage:");
              out("\tjava SimpleAudioRecorder -h");
              out("\tjava SimpleAudioRecorder <audiofile>");
              System.exit(0);
         private static void out(String strMessage)
              System.out.println(strMessage);
    }Daniel

  • Get a list of objects from an array

    I'm having trouble getting a list from an array.  I have an array (cardArray) that I load up with movieclips.
    I create the instances via: var card_01:RallyChaseCard = new RallyChaseCard();, card_02 etc.
    I want to be able to run a trace on the array and get a current listing and order of the cards inside.
    When I run trace(cardArray) all I get is a list like this:
    [object RallyChaseCard],[object RallyChaseCard],[object RallyChaseCard]
    How do I get it to list the contents buy their card names?
    This is one of those things that seems like it ought to be so obvious, yet is eluding me and my trial and error attempts to solve it.

    create a name property in your class and assign a name property to your instances (either in the contructor) and/or using getters/setters.  (you'll need a getter anyway.)

  • Creating PDF's from *.doc or *.docx file with fake security issue's ......

    Hi,
    We're trying the new 11 Pro and just patched it to:11.0.09 to try to fix this error below.
    When the user tries to create a PDF from the main menu that now says "Create PDF from File" instead of the old screen that said "Create PDF" ......
    If I start the process with a *.docx file I get the " can't open the file because of rights "  error and it was doing the same thing in the old original installed
    version of 11 and also now this the new one I just updated now to try to fix it. 
    I also deleted the normal.doc templates in both his old MS Word 2003 program and also in the current copy he uses MS Word 2007.
    If I start the 11 Pro and pick the same document as the first one except for the fact that it has been re-saved in a *.doc MS Word 2003 format,
    the whole thing works perfectly.
    Any suggestions?
    Cheers'
    Dave

    Have you tried to open WORD and either print to the Adobe PDF printer or use the Acrobat icon (PDF Maker)? Try both. Do they work or not. PDF Maker has to work for the functionality of the create in Acrobat to work.

  • Create an image from float array?

    Dear All,
    I have a float array containing pixel values. From that array I want to create an image (let's say in JPEG format).
    How should I do that?
    thanks

    Hi musti168,
    You're going through your entire image pixel-by-pixel and getting each of their values - why don't you just use the IMAQ ImageToArray function?  
    On this forum post I found an example of IMAQ ArrayToImage: http://forums.ni.com/t5/LabVIEW/IMAQ-arraytoimage-​example/td-p/68418
    You can use some of the IMAQ Image Processing palette to change the image to gray scale - possibly a threshold.
    Julian R.
    Applications Engineer
    National Instruments

  • Error while Transport objects from DEv to QA-File transport

    Hai Experts!
    While exporting objects from Dev to Quality using File Transport. it taking long time and no erro msg is thown and it is not getting end .Did any face this problem. Can any one help me to solve this.
    Regard's
    Preethi.

    Hai!
    Issue is solved.
    I try to export the Individual object -->Message mapping.
    While exporting i unchecked the Option With software component version Defenition.
    Now it is success. Thanks all replies.
    Regard's
    Preethi.

  • Creating a String from an array of characters.

    Hi,
    i'm trying to make a string from an array of characters, this i've managed:
    char data[] = new char[x];
    String str = new String(data);My problem is this: Let's say the array of characters has space for 10 chars, but i only input 5, when i convert it to a string, the 5 characters show up fine, but the last remaining characters show up as little boxes ( [] [] [] [] [] ) .
    It there a way to remove these?
    Thanks in advance
    Mike

    jverd wrote:
    georgemc wrote:
    String str = new String(data).trim();
    Does the null character count as whitespace?Seems to. Actually, I'm getting different results depending on the compiler used.
    public static void main(String[] args) {
              char[] c = new char[10];
              for(int i = 0; i < 5; i++) {
                   c[i] = (char) ('a' + i);
              String first = new String(c);
              System.err.println("[" + first  + "]");
              System.err.println(first.length());
              String second = new String(c).trim();
              System.err.println("[" + second  + "]");
              System.err.println(second.length());
         }ECJ-compiled output:
    >
    [abcde
    10
    [abcde]
    5
    >
    javac-compiled output:
    >
    [abcde]
    10
    [abcde]
    5
    >
    Odd

  • I want to create a 3*3 multidimensional array of label objects

    i want to initialize the array with label objects help me

    If this post answers your question or helps, please mark it as such.
    <?xml version="1.0"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
      creationComplete="init();">
      <mx:Script>
        <![CDATA[
          import mx.controls.Label;
          private var arr:Array = new Array();
          private function init():void{
            for(var a:uint=0;a<10;a++){
              var inArr1:Array = new Array();
              for(var b:uint=0;b<10;b++){
                  var inArr2:Array = new Array();
                for(var c:uint=0;c<10;c++){
                  var lbl:Label = new Label();
                  lbl.text = "Label" + a + b + c;
                  inArr2.push(lbl);
                inArr1.push(inArr2);
              arr.push(inArr1);
            for each(var xArr:Array in arr){
              for each(var yArr:Array in xArr){
                for each(var lbl2:Label in yArr){
                  txt.text += lbl2.text + " ";
        ]]>
      </mx:Script>
      <mx:TextArea width="100%" height="100%" id="txt"/>
    </mx:Application>

  • Remove an object from PDF-generated XML file

    Hi,
    In a stage of user workflow of my PDF, the user presses a submit button that sends XML data to an address. There's an image field that has hundreds of lines of XML code that has no need to sent.  In fact, by the time this submit button is pressed, the image field is already "hidden", but of course it remains on the form.
    Is there any sort of visibility or access property that will supress an object enough that it doesn't transfer with XML?  How about dynamically deleting a field on the user-end?

    Hi,
    One solution, use an ImageField object instead of an Image object. Then go to the Object > Binding palette and for the binding select No Data Binding (or None, depending on your version of LC Designer).
    Because you are now using an ImageField you will need one line of code in it's docReady event (JavaScript):
    this.access = "readOnly";
    The lines in the XML data file contain the image in Base64 format.
    Hope that helps,
    Niall

  • How to decide if Object is an array or single object

    Hi ,
    I have a function which can return an Array of objects or a single Object...how can I decided what function has returned to me.?...
    I am looking for some way by which I can decided if it is an Array or a Object....
    Thanks

    How about:
    yourObject.getClass().isArray();  // returns boolean

  • Generate java objects from one single XML file

    Hi,
    I want to create an XML file that describes a set of "messages" (see XML below).
    I want to generate the objects "Message" with simple getters and setters for each <message> entry.
    And a little bit more complicated, I need to generate an object "Action" that will parse an incoming message based on the fields and rules described in the XML.
    XML file:
    *<messages>*
    *<message>*
    *<name>PrivateMessage</name>*
    *<fields>*
    *<receiver maxlength="32" minlength="4"/>*
    *<sender maxlength="32" minlength="4"/>*
    *<content minlength="1"/>*
    *</fields>*
    *</message>*
    *<message>*
    *<name>MessageToAll</name>*
    Message object:
    Example:
    public class MessagePrivateMessage extends Message {
         private String sender;
         private String receiver;
         private String message;
         /* all the getters and setters for the fields above */
    Action object:
    The Action will parse an incoming message based on the rules in the XML above, and create the Message object; e.g. :
    <sender maxlength="32" minlength="4"/>
    will result to
    String sender = getNextField(fields);
    if (sender == null || sender.trim().equals("")) {
         throw new InvalidMessageException("Sender username null");
    if (sender.length() > 32 || sender.length() < 4) {
         throw new InvalidMessageException("Sender username exceeds 32 characters: " + sender);
    Example:
    public class ActionPrivateMessage extends ActionReceiveClient<MessagePrivateMessage> {
         public ActionPrivateMessage() {
         public void execute(LinkedList<String> fields, EndpointServer server, int idMessage, Object stream, Date dateRead)
                   throws InvalidMessageException {
              MessagePrivateMessage dtoMessage = new MessagePrivateMessage();
              dtoMessage.setDateServerRead(dateRead);
              dtoMessage.setId(idMessage);
              dtoMessage.setStream(stream);
              parseMessage(fields, dtoMessage);
              dtoMessage.setDateServerParsed(new Date());
              server.sendPrivateMessage(dtoMessage);
         public void parseMessage(LinkedList<String> fields, MessagePrivateMessage dto)
                   throws InvalidMessageException {
              super.parseMessage(fields, dto);
              String sender = getNextField(fields);
              if (sender == null || sender.trim().equals("")) {
                   throw new InvalidMessageException("Sender username null");
              if (sender.length() > 32 || sender.length() < 4) {
                   throw new InvalidMessageException("Sender username exceeds 32 characters: " + sender);
              String receiver = getNextField(fields);
              if (receiver == null || receiver.trim().equals("")) {
                   throw new InvalidMessageException("Receiver username null");
              if (receiver.length() > 32 || receiver.length() < 4) {
                   throw new InvalidMessageException("Receiver username exceeds 32 characters: " + receiver);
              String message = getNextField(fields);
              if (message == null || message.trim().equals("")) {
                   throw new InvalidMessageException("Message null");
              if (message.length() < 1) {
                   throw new InvalidMessageException("Message exceeds 200 characters: " + message);
              if (!fields.isEmpty()) {
                   String remainingFields = "";
                   while (!fields.isEmpty()) {
                        remainingFields += fields.remove(0) + " ";
                   throw new InvalidMessageException("Fields remaining but everything has been parsed: " + remainingFields);
              dto.setSender(sender);
              dto.setReceiver(receiver);
              dto.setMessage(message);
    First question, is it possible ?
    Second one would be, how ? Any tips ?
    Thank you for any help :)

    matthew_be wrote:
    First question, is it possible ?Sure, why not.
    Second one would be, how ?Well, I think the standard way is to write the required code.
    If you really can't come up with a way, then you probably shouldn't be trying to implement such a thing.
    Any tips ?Before I would start writing my own framework for something like that, I'd take a look at all the existing Java/XML technologies out there (of which there are a bunch). Either an existing framework will solve your problem or it will prove to be helpful in your own implementation.

  • How do I create a pdf from a large jpeg file

    I am trying to convert a 20MB jpeg file into PDF using acrobat but I get an error that says the file is either not supported or is a corrupted/damaged file. However, I can open the jpeg in windows image viewer and photoshop.
    Why not convert it in photoshop you ask? This is because every time I try to save a large file as pdf in photoshop, I get a corrupted file. I get the error "out of memory" when I try to open the file.
    The 20MB jpeg file was originally a psd file, saved as jpeg and now being converted to pdf. Questions:
    Is there a file size limit to convert to pdf in acrobat?
    Why are my pdf files saved from photoshop saying 'out of memory'?

    Hello,
    I was able to receive help from Adobe chat and resolve the issue. I did not get any answers as to why I was getting the error message. But to get around the error message, these are the steps:
    1. Save image as Jpeg (in photoshop or whatever)
    2. In windows explorer, right-click on jpeg file and click "open file with" and choose Adobe Acrobat
    3. Once the file is open in Acrobat, File > Save (not save as) then save in desired file name.
    This is another option to save jpegs as PDFs. An even better option for saving images into PDFs is to save the file as Photoshop EPS format in photoshop, you can then open it in Acrobat to save as a PDF. While saving as Jpeg and converting to pdf yielded a ~15mb file, saving the files as a PhotoshopEPS first then converting it to PDF yields a smaller file, at ~9mb. Still the same quality.

  • Creating a PDF from a series of files

    I am supposed to create a PDF of files , where do I start?
    10.6.8

    This may not be exactly what you want, but perhaps a start.
    See this link.  http://www.itcs.umich.edu/itcsdocs/s4308/

  • Functions in a For Loop defining objects from an Array. . .Why Won't This Work?!

    I'm trying to put these functions into a Loop to conserve
    space. Why won't this work?
    .

    Yeah, sly one is right. You can not have the "i" inside the
    onRollOver function, what you have to do is: As the movieClip class
    is dynamic you can create a property of the movieClip which stores
    the value if the "i". And then, inside the onRollOver function, you
    have to make reference to that property.
    for (i=0; i<2; i++) {
    this.regArray
    .iterator = i;
    this.regArray.onRollOver = function () {
    showRegion(regArray[this.iterator]);
    this.regArray
    .onRollOut = function () {
    hideRegion(regArray[this.iterator]);

Maybe you are looking for

  • Transferring Album Art from a Mac to a Windows PC

    I have iTunes on both my Mac and Windows PC- with the same library on both. I found a great utility called Curator that found all my missing album art on the Mac, but it only works on the Mac, not the PC So after spending a day finding all my missing

  • I re installed fire fox and i still get a firefox.exe has encountered a problem and must close

    i get a sign that sez firefox exe. has encountered a problem and nneds to close....no matter which little sign i hit ...send error report or dont send error report.....mozilla closes ! it also sez to contact microsoft...when i did they could not help

  • How To Play The Shuffle Thru A Boombox Or Stereo?

    I was wondering if it's possible to directly plug in the shuffle and play it using the speakers in my Sony boombox or through my stereo system - and what parts would be needed to do it?

  • Customizing Oracle ADF Default Skins

    Hello, My JDeveloper Version is 11.1.2.1.0. R2 Is there any tutorial about Customizing oracle adf default skins. For Example I want to change some CSS Properties of "Simple" Skin. I know I can change some properties by using Inline styles but it is n

  • RAID for secondary drives?

    Hey all, I was just curious about something.  I have a KT3-Ultra2 with RAID but have never used RAID before.  I got this board because I thought I'd try it. My system runs off a 30 gig drive, but I thought it would be nice to have mirrored raid drive