Reflection - How to provide qualified path to class?

Hello folks,
I am writing the application in which user will be able examine any java class at any mapped drive at his PC.
The snipplet is as follows:
import java.lang.reflect.*;
public class ClassInfo {
public static void main( String[] args ) throws Exception {
Class theClass = Class.forName(args[0]);
System.out.println("Class Name: " + theClass.getName());
//Other methods go here
(In GUI application I will provide a FileChooser, of course.)
It works perfectly well as long as the class I want to examine is in the same folder. Example below.
C:\MyFolder>java ClassInfo MyClass
Class Name: MyClass
But when I try to provide the full path to the class outside of that folder - it did not work at all. I am getting ClassNotFound exception. I tried every possible way, such as "C:\\myFolder2\\myClass2� and
"myFolder2.myClass2", etc.
Does someone know how to circumvent this obstacle?
Many thanks at advance.
Vlad

Thank you very much, guys, for your responses. I figured it out. Hopefully, my code will be useful for someone else.
The only limitation is: In the current version it does not handles packages, in other worlds, if the class is a part of a package, such as
package hello;
public class HelloFromHell{
//the rest of the class
I am getting error messge:
Exception in thread "main" java.lang.NoClassDefFoundError: HelloFromHell (wrong name: hello/HelloFromHell) It expects to find the class name in the directory named "hello", which is a package name.
Vlad
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import javax.swing.*;
public class ClassInfo {
static void displayClassInfo(File file) {
//Get Directory info
File directory = file.getParentFile();
//Get Class name without ".class" ext
String className = file.getName().substring(0,file.getName().length() -".class".length());
try {
//Create the URLClassLoader
URL[] theURL = {directory.toURL()};
URLClassLoader loader1 = new URLClassLoader(theURL);
//Pass class name loader to the forName method
Class theClass = Class.forName(className, true, loader1);
System.out.println("Directory: " + directory.toURL());
System.out.println("Class: " + theClass.getName());
Method[] theMethods = theClass.getDeclaredMethods();
System.out.println("Methods:");
System.out.println("-------");
for (int i = 0; i < theMethods.length; i++) {
System.out.println("Name: " + theMethods.getName());
System.out.println();
//Other reflection methods go here as needed
catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
System.err.flush();
catch (java.net.MalformedURLException mue) {
System.err.println(mue);
System.err.flush();
//Helper method to prevent user from selecting anything but java classes
static boolean isClass(String fileName) {
if (fileName.endsWith(".class")) {
return true;
return false;
//Method to call JFileChooser dialog thus preventing users from typing
public static void main(String[] args) {
// display a file dialog to the user for file selection
JFileChooser fileChooser = new JFileChooser(System.getProperty("user.dir"));
if (JFileChooser.APPROVE_OPTION == fileChooser.showOpenDialog(new JFrame())) {
if ( (fileChooser.getSelectedFile().getName() != null) &&
(isClass(fileChooser.getSelectedFile().getName()))) {
displayClassInfo(fileChooser.getSelectedFile());
else {
//Handle errors gracefully
System.out.println("No file was selected or file is not a java class.");
System.exit(0);

Similar Messages

  • How to Provide File Path in MII 12 to access file located in Network Path

    Hi,
    How can I locate a file which is placed Network Path?
    Iam trying to access PDF file which is stored in Network Drive, I just want to open folder which contains all PDF files located in some Network Path on click of button.
    I tried all possibilities like below:
    window.open("file
    \G:");
    window.open("
    SERVER-NAME
    Folder Name");
    But Iam unable to Fix this.
    Please Help me in this regard
    Regards,
    Padma

    Hi Rao,
    this is less a MII than a browser or mapping problem.
    You can access a local file in a browser like this:
    window.open('file:///c:/folder/file.txt');
    However, in case of MII local means local to the MII server. So in the above example the file is located on the c driver of the MII server.
    If you want to access files on a network drive, the folders to the files should be mapped on the MII server so you are able to address them like they were local files.
    I haven't tried to address network folders directly, because we are running MII on Unix.
    Michael

  • Loading a class via reflection without knowing the full qualified path ?

    Hi there
    I d like to load a class via reflection and call the constructor of the class object. My problem is that I dont know the full qulified name e.g. org.xyz.Classname bur only the Classname.
    I tried different things but none seem to work:
         1. Class c = Class.forName("Classname");  //does not suffice, full qualified name required
    2. ClassLoader classloader = java.lang.ClassLoader.getSystemClassLoader();
             try {
               Class cl = classloader.loadClass(stripFileType(Filename));//if i do not pass the full qualified name i get a ClassNotFoundException
    3. I tried to consruct a class object with my own classloader , calling:
              Class cl = super.defineClass(null, b, 0, b.length );     b is of type byte[]This almost works. I get a class Object without knowing the full qulified path. I can transform a filename into a raw array of bytes and I get the class out of it. But there is still a problem: If there are more than on classes defined in the same textfile I get an InvocationTargetException.
    It looks like this:
    package org.eml.adaptiveUI.demo;
    import com.borland.jbcl.layout.*;
    import java.awt.*;
    import org.eml.adaptiveUI.layout.*;
    import javax.swing.*;
    import java.awt.event.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2003</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class twoButtons extends JFrame {
      SPanel sPanel1 = new SPanel();
      JButton jButton1 = new JButton();
      GridBagLayout gridBagLayout1 = new GridBagLayout();
      GridBagLayout gridBagLayout2 = new GridBagLayout();
      public twoButtons() throws HeadlessException {
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      public static void main(String args[]){
        twoButtons twob = new twoButtons();
        twob.pack();
        twob.show();
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(gridBagLayout1);
        jButton1.setText("button 1");
        jButton1.addActionListener(new TransformationDemo_jButton1_actionAdapter(this));
        this.getContentPane().add(sPanel1,  new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
                ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(57, 52, 94, 108), 35, 44));
        sPanel1.add(jButton1,  new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
                ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 41, 0, 0), 0, 0));
      void jButton1_actionPerformed(ActionEvent e) {
        System.out.println("button 1 source: " + e.getSource());
        System.out.println("d: " + e.getID());
       System.out.println("/n commmand: " + e.getActionCommand());
    class TransformationDemo_jButton1_actionAdapter implements java.awt.event.ActionListener {
      twoButtons adaptee;
      TransformationDemo_jButton1_actionAdapter(twoButtons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton1_actionPerformed(e);
    }As you can see there is the class TransformationDemo_jButton1_actionAdapter class defined in the same classfile. The problem is now that the twoButtons constructor calls the TransfomationDemo_jButton1_actionAdapter constructor and this leads to InvocationTargetException. I dont know if this is a java bug because it should be possible.
    Can you help me?

    hi thanks at first,
    the thing you mentioned could be a problem, but I dont think it is.
    If I have the full qualified name (which I havent) then everything goes normal. I only have to load the "twoButtons" class and not the other (actionadapter class), so I dont think this is the point. In this case the twoButtons constructor constructs an object of the actionadapter class and everything goes well. The bad thing is though that I do not have the full qulified name :(
    Invocation target exception tells me (in own words): Tried to acces the constructor of the actionadapter class (which is not public) out of class reflectionTest class .
    reflectionTest is the class where the reflection stuff happens and the twoButttons class is defineClass() ed.
    The problem is, only twoButtons class has the rights to call methods from the actionadapter class, the reflection class does not. BUT: I do not call the actionadapter methods from the reflection class. I call them only from the twoButtons class.
    I hope somebody understands my problem :)

  • How to add external library in class path folder for use in Java call-out?

    Hi,
    I am working with Java callout component in OSB 12c using Jdeveloper.
    Thing is Jar what i am using to perform conversion of json to xml that using external libraries.
    When i have give reference of my project jar to java callout it doen't found external libraries.
    Could you please tell me how to add external libraries in class path folder or How to use to add it through web-logic server ?
    Thanks,
    Pavan

    Hi,
    Thanks, I have solved issue.
    We can add on following path in windows pc:
    C:\Users\your_usename\AppData\Roaming\JDeveloper\system12.1.3.0.41.140521.1008\DefaultDomain\lib
    One you add your external lib here then do restart weblogic server instance.
    Now, you have that external lib or jar in use.
    Cool!

  • Sun ONE Studio 4 aka Forte: How to set the output path for classes ?

    Help !
    Beginner's question:
    Sun ONE Studio 4 aka Forte:
    How to set the output path for classes ?
    As default, the class files are created in the same directory as the
    sources.
    In opposite, both JBuilder and Together support that there is a tree
    with the sources and another tree with the classes.
    The first answer I got was "not possible with Forte, but just if you write your own "ANT Build script" !
    a) Please point me to a ready-to-use ANT script for this purpose, if such is available
    b) Is using ANT instead of the MAKE as comfortable ? Besides the separation of sourcecode and classes, I would like to keep everything else to be the same, i.e. I don�t want to edit the ANT file if I enlarge the project by directories or files.
    Tia
    Sincerely
    Rolf

    You can set S1S's options to place newly created .class files in a specific location.
    Identify the compiler that is being used - Open the S1S's Tools/Options window, expand Editing and select Java Sources. Note the Default Compiler value. (If it's one if the Ant options, you use Ant to specify this option, not S1S.)
    Open the S1S's Tools/Options window, expand Building/Compiler Types and select the appropriate compiler.
    The Properties tab of the compiler has the property Target, which sets the filesystem where the compiler output is directed. If you choose <not set>, the .class files are written to their source directory.
    When you set the Target, your change affects all classes that use this compiler.
    Very few options can't be set in S1S; the challenge is finding out where they're set!

  • How service Provider Provide MPLS different level of Class of Service!!!

    Hi Team,
    Most of the time Service provider says that they can provide any class of service and any level (CoS1 to N)...On a global setup, how Service Provider Core is being provisioned to provide this kind of scalability and redundancy...I am interested in mainly the core Cloud of Service provider not the PE...Any docs or link will be of gr8 help...Service provider will no away running 50% of their capacity and provide redundancy..So there should be some tweking which allow them to Provide different level of SLA..How need to know..
    Thanks in advance..
    With best regards,
    Mani

    1) Irrespective of how many ever COS they are providing/selling for the Customer at the Edge most SP will have only 4 to 5 major classes in the core, and the SLA provided on DSCP,COS,PREC are merged into these super classes where they map to.
    2) The question of BW of 50% this is subjective to each SP, just like you have a pipe of 1 gig for Internet in what ratio would you sell this BW is subjective to each SP. SImilarly when you provide SLA with certain guranteed uptime, the bandwdith availability during backup is considered and the its generally sold in the same ratio.
    If the ratio at which the BW is sold at the edge, exceeds the available 50% during failure, then olny your upper higher priority classes get tranmistted. But this is seldom recommended.
    HTH-Cheers,
    Swaroop

  • Unable to load your custom module provider's module-factory-class

    I am having a problem while I deploy my application. it gives me following error:
    Unable to load your custom module provider's module-factory-class com.bea.p13n.descriptor.module.ConfigModuleFactory
    Dont know how to resolve it. the class is in p13n_system.jar file, I have added that jar as a library in deployment but still it shows the same error.
    Added it in classpath as well but same error. (Dont know exactly how to add in class path, i have added just in "Start Server" tab's classpath)
    Any help will be greatly appreciated

    Below link might be helpful.
    http://kr.forums.oracle.com/forums/thread.jspa?threadID=1049509&tstart=0
    Regards,
    Anandraj
    http://weblogic-wonders.com/

  • How to find out logs related to which server, If i have 2 WFE's in the farm. How to configure logs path?

    Hi,
    I got this doubt, when searching logs on the servers. I have 2 WFE's in my farm, I got an error from enduser. So in which WFE server i need to check the logs.
    How to configure logs path. Is it is possible to specify logs path on our own instead of 14 hive folder.
    Badri

    That is a really bad idea, especially with idle disconnects and other unreliability of CIFS.
    You should instead check out the command
    Merge-SPLogFiles which will allow you to combine ULS logs from multiple servers into a single file.
    You can certainly specify your own path, but the path must be available on all servers. For example, if you specified D:\Logs, D:\Logs must exist on all SharePoint servers within the farm.
    Trevor Seward
    Follow or contact me at...
    &nbsp&nbsp
    This post is my own opinion and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs.

  • How to get the path when i select a directory or a file in a JTree

    How to get the path when i select a directory or a file in a JTree

    import java.lang.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.HeadlessException;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Iterator;
    * @author Frederic FOURGEOT
    * @version 1.0
    public class JTreeFolder extends JPanel {
    protected DefaultMutableTreeNode racine;
    JTree tree;
    protected JScrollPane scrollpane;
    final static int MAX_LEVEL = 1; // niveau max de descente "direct" dans l'arborescence
    * Sous-classe FSNode
    * @author Frederic FOURGEOT
    * @version 1.0
    private class FSNode extends DefaultMutableTreeNode {
    File file; // contient le fichier li� au noeud
    * Constructeur non visible
    private FSNode() {
    super();
    * Constructeur par initialisation
    * @param userObject Object
    FSNode(Object userObject) {
    super(userObject);
    * Constructeur par initialisation
    * @param userObject Object
    * @param newFile File
    FSNode(Object userObject, File newFile) {
    super(userObject);
    file = newFile;
    * Definit le fichier lie au noeud
    * @param newFile File
    public void setFile(File newFile) {
    file = newFile;
    * Renvoi le fichier lie au noeud
    * @return File
    public File getFile() {
    return file;
    public JTree getJTree(){
         return tree ;
    * Constructeur
    * @throws HeadlessException
    public JTreeFolder() throws HeadlessException {
    File[] drive;
    tree = new JTree();
    // cr�ation du noeud sup�rieur
    racine = new DefaultMutableTreeNode("Poste de travail");
    // cr�ation d'un noeud pour chaque lecteur
    drive = File.listRoots();
    for (int i = 0 ; i < drive.length ; i++) {
    FSNode node = new FSNode(drive, drive[i]);
    addFolder(drive[i], node); // on descend dans l'arborescence du lecteur jusqu'� MAX_LEVEL
    racine.add(node);
    // Gestion d'evenement sur JTree (on �coute les evenements TreeExpansion)
    tree.addTreeExpansionListener(new TreeExpansionListener() {
    public void treeExpanded(TreeExpansionEvent e) {
    // lorsqu'un noeud est ouvert
    // on descend dans l'arborescence du noeud jusqu'� MAX_LEVEL
    TreePath path = e.getPath();
    FSNode node = (FSNode)path.getLastPathComponent();
    addFolder(node);
    ((DefaultTreeModel)tree.getModel()).reload(node); // on recharche uniquement le noeud
    public void treeCollapsed(TreeExpansionEvent e) {
    // lorsqu'un noeud est referm�
    //RIEN
    // alimentation du JTree
    DefaultTreeModel model = new DefaultTreeModel(racine);
    tree.setModel(model);
         setLayout(null);
    // ajout du JTree au formulaire
    tree.setBounds(0, 0, 240, 290);
    scrollpane = new JScrollPane(tree);
         add(scrollpane);
         scrollpane.setBounds(0, 0, 240, 290);
    * Recuperation des sous-elements d'un repertoire
    * @param driveOrDir
    * @param node
    public void addFolder(File driveOrDir, DefaultMutableTreeNode node) {
    setCursor(new Cursor(3)); // WAIT_CURSOR est DEPRECATED
    addFolder(driveOrDir, node, 0);
    setCursor(new Cursor(0)); // DEFAULT_CURSOR est DEPRECATED
    * Recuperation des sous-elements d'un repertoire
    * (avec niveau pour r�cursivit� et arr�t sur MAX_LEVEL)
    * @param driveOrDir File
    * @param node DefaultMutableTreeNode
    * @param level int
    private void addFolder(File driveOrDir, DefaultMutableTreeNode node, int level) {
    File[] fileList;
    fileList = driveOrDir.listFiles();
    if (fileList != null) {
    sortFiles(fileList); // on tri les elements
    // on ne cherche pas plus loin que le niveau maximal d�finit
    if (level > MAX_LEVEL - 1) {return;}
    // pour chaque �l�ment
    try {
    for (int i = 0; i < fileList.length; i++) {
    // en fonction du type d'�l�ment
    if (fileList[i].isDirectory()) {
    // si c'est un r�pertoire on cr�� un nouveau noeud
    FSNode dir = new FSNode(fileList[i].getName(), fileList[i]);
    node.add(dir);
    // on recherche les �l�ments (r�cursivit�)
    addFolder(fileList[i], dir, ++level);
    if (fileList[i].isFile()) {
    // si c'est un fichier on ajoute l'�l�ment au noeud
    node.add(new FSNode(fileList[i].getName(), fileList[i]));
    catch (NullPointerException e) {
    // rien
    * Recuperation des sous-elements d'un noeud
    * @param node
    public void addFolder(FSNode node) {
    setCursor(new Cursor(3)); // WAIT_CURSOR est DEPRECATED
    for (int i = 0 ; i < node.getChildCount() ; i++) {
    addFolder(((FSNode)node.getChildAt(i)).getFile(), (FSNode)node.getChildAt(i));
    setCursor(new Cursor(0)); // DEFAULT_CURSOR est DEPRECATED
    * Tri une liste de fichier
    * @param listFile
    public void sortFiles(File[] listFile) {
    triRapide(listFile, 0, listFile.length - 1);
    * QuickSort : Partition
    * @param listFile
    * @param deb
    * @param fin
    * @return
    private int partition(File[] listFile, int deb, int fin) {
    int compt = deb;
    File pivot = listFile[deb];
    int i = deb - 1;
    int j = fin + 1;
    while (true) {
    do {
    j--;
    } while (listFile[j].getName().compareToIgnoreCase(pivot.getName()) > 0);
    do {
    i++;
    } while (listFile[i].getName().compareToIgnoreCase(pivot.getName()) < 0);
    if (i < j) {
    echanger(listFile, i, j);
    } else {
    return j;
    * Tri rapide : quick sort
    * @param listFile
    * @param deb
    * @param fin
    private void triRapide(File[] listFile, int deb, int fin) {
    if (deb < fin) {
    int positionPivot = partition(listFile, deb, fin);
    triRapide(listFile, deb, positionPivot);
    triRapide(listFile, positionPivot + 1, fin);
    * QuickSort : echanger
    * @param listFile
    * @param posa
    * @param posb
    private void echanger(File[] listFile, int posa, int posb) {
    File tmpFile = listFile[posa];
    listFile[posa] = listFile[posb];
    listFile[posb] = tmpFile;

  • How to detect the path of Temp directory

    I am writing a class library which allows users to manipulate a database in the web server java applications/applets. In my logic the Application/Applet communicate with a CGI script/Servlet in the server and that do all the database handling. My objective is to make the Client independant from the Database Drivers, and to some restrictions and possible security threats that can arrice when accessing the database directly.
    99% of the work is done and now I am doing the fine tuning.
    My Problem:
    When the user downloading a blob object from the server database. each time the program read the blob it will get a new copy from the server. This is not good if the blob is large (few 100 megs) . So I am going to implement a cache system. but the problem is If I am caching in the memory it will not support large objects (Memory is a limited factor). So the preferance is use the Temperary files but I do not know how to detect the path to temperary folder.
    And my 2nd questions is are the applets allowed to write and read in temperary folder.

    The Java default temporary file path can be determined with
    System.getProperty("java.io.tmpdir")This is typically the same value as the os environment variable

  • How to know the path of file.

    i am facing a problem,i have prepared a jar file of an application, which should have a path-file in it & that path-file contains loaction from where applicatioin starts, and creates some file there. but i dont know loaction when i prepared the jar file.how to solve this problem.

    but it is not in my hand, My jar file will be used by a vendor to code a Servlet which will access the classes in the jar file. it cannot be solved by My jar file.
    My Question was
    I have to deliver a jar file which contains my classes. This jar file will be used by a vendor to code a Servlet which will access the classes in the jar file.
    One of the classes in this jar file is required to simulate a file-system (we call it "Repository"). Essentially, it creates a certain directory and reads-writes files into it.
    My problem is how to specify the path (i.e. directory location) of the "Repository". Following are the possibilities I could see :
    1. Hardcode the path in the java code - This is not desirable since we do not know it while I am preparing my jar-file.
    2. Create a properties file, put Repository.path=... as an entry and package it with the jar-file - The problem is that sine this properties file is packaged in the jar, it is read-only. Hence, it cannot be changed at runtime.
    I want to know what are the general approaches to this?

  • How to determine the path of the jar file cache of javawebstart?

    Hello, I need to know how to determine where the java web start application
    file jar cache is stored on windows system hard drive.
    I would have launch of the inner processes
    I have need to know the path of file jar .
    example if my application is myAppliation.jar
    in code generic class of myAppliation.jar i have the command runtime
    String strCmd =
    System.getProperties().getProperty("java.home") + "\\bin\\java" +
         " -cp " +
         System.getProperties().getProperty("java.class.path") + ";"
         + " anotherClass.class ";
    Runtime.getRuntime().exec(strCmd);
    the anotherClass.class has need
    of the contained library in myAppliation.jar.

    Thanks i have tried this metod and function
    java.net.URL resource = classLoader.getResource("myResource");
    if (resource != null) {
    String s = resource.toString();
    if (s.startsWith("jar:")) {
    int index = s.indexOf("!");
    if (index > 4) {
    String fileurl = s.substring(4, index);
    if (fileurl.startsWith("file:")) {
    String path = fileurl.substring(5);
    // now path is the path to the jar file in the cache containing the resource
    System.out.println("file jar: "+path);
    }

  • How to set classpath from java class ??

    I have tried to use System.setProperty("java.class.path", "my class path string ") to set classpath dynamically. But it is not working. How to set it dynamically from java class ?? Thanks , gary

    Look into the java.net.URLClassLoader. You can't set the classpath after the fact but you can specify URL's that will checked when you try to load a class with that loader.

  • How can I call a nonstatic class

    Hello All,
    I've wrote a simple bean for my testcase that count a value (e.g. site access):
    public class Bean1 {
    private int accessCount = 1;
    public int getAccessCount() {
    return (accessCount++);
    If I call the bean with a jsp-site, it works fine with different scope. e.g. session and application.
    With session scope different browser count different. With application scope different bowser count together. Thats the normal attitude.
    My jsp code:
    <jsp:useBean id="counter" class="ml.view.Bean1" scope="session" />
    <jsp:getProperty name="counter" property="accessCount" />
    This don't work with a static bean (normal too), but I can only call a static class in my UIX site.
    I call the bean from uix with the invoke element. Is that correct? How can I call a nonstatic class with a special scope? Which other solution ist possible?
    My uix code:
    <invoke method="getAccessCount" result="${uix.eventResult.getAccessCount}" instance="${sessionScope.myBean.getAccessCount}" exception="${uix.eventResult.error}" javaType="ml.view.myBean"/>
    Thank you for any solution!
    The error messages are:
    java.lang.NullPointerException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java)
    at oracle.cabo.servlet.event.InvokeEventHandler._invoke(Unknown Source)
    at
    and so forth...

    false in my uix code example: javaType="ml.view.myBean"
    correct: javaType="ml.view.Bean1"
    Sorry :-) that was only an error in my post not in the really example.

  • How to remember the path while traverse a binary tree?

    Hi, again, I have difficulty handling tree search problems.
    The quesion is How to search for a node from a binary tree A, return true if found meanwhile generate the path which can be used to locate the node.
    I think the signature should be:
    // The path contains only 0s and 1s. 0 means go left and 1 means go right.
    public staic boolean search(Node rootOfA, Node b, ArrayList<Integer> path){
    // the class Node only has two fields:
    Node{
    Node left;
    Node right;
    I know if there is another field in the Node class (say, a flag), the quesion would be much easier, but the space is really critical.
    I tried to use recursion but havn't got a correct solution. I am thinking of usinga non-recursion algo.
    Anyone wants to help?

    Hi, JosAh,
    That's mind provoking. However, I do think it works. It does not pop some stuff it should pop. I tested it over a very simple tree and it failed. Did you test it? I might be wrong...
    The tree I am working on does not have null pointers, the condition to test if a node is a leaf is if(node.right == right). Namly, all the right pointer of leaves points to itself.
    So I changed your code to be:
    Stack search(Node root, Node node, Stack<Integer> path) {
         if (root == null || root.right ==right) return null;
         if (root.equals(node)) return path;
         path.push(0);
    if (search(root.left, node, path) != null) return path;
    path.pop();
    path.push(1);
    return search(root.right, node, path);
    }I simply tested it with
    Stack<Integer> path = new Stack<Integer>();
    System.out.println( root, root.right.right, path);
    root is the root of a complete binary tree with 7 nodes(4 leaves).
    Apparenly, if the path is built correctly search(root, root.right.right, path) would return [1,1] whereas this seach returns [ 0 , 1, 1].
    Considerring , the right branch never pops, I changed it into
    Then I changed it to :
    Stack search(Node root, Node node, Stack<Integer> path) {
         if (root == null || root.right ==right ) return null;
         if (root.equals(node)) return path;
         path.push(0);
    if (search(root.left, node, path) != null) return path;
    path.pop();
    path.push(1);
    if (search(root.right, node, path) != null) return path;
    path.pop();
    return path;
    With the same test case, it returns [].
    I will keep working on it.
    Cheers,
    Message was edited by:
    since81
    Message was edited by:
    since81

Maybe you are looking for

  • HT1349 How can i find out the size and length of my playlist?

    How can i find out the size and length of my playlist? Anybody?

  • Delivery Notification: Delivery has failed

    I keep receiving a "Delivery Notification: Delivery has failed" message about a message that I apparently sent 4 years ago. How can I stop it? Also please see notes at bottom of post! thanks and regards vats3 Delivery Notification: Delivery has faile

  • US TIN in Canadian vendor master data

    Hi all, Our US Cocd work with Canadian vendors. We don't know which field should be displayed on tx FK01 to allow the USA TIN be entered in Canadian vendors master data? I mean: which is the field status we should modify to optional in tx. OBD3-Creat

  • Disable DVD Fan?

    I recently had my computer into the Genius Bar to diagnose a loud buzzing in the computer. It's a DVD (Optical) Fan. I couldn't be without my computer for the two or three days it would take them to fix it, so I left with the assurance that even if t

  • Adobe concern

    You know I am really concerned about all this Adobe stuff. Adobe Air (what is that and do I need it?), Flash, Shockwave Player, Reader. Secunia is showing all of these as category 4 threats, and the Reader as a category 5 threat stating that hijacker