Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have been trying to set the class path programmatically using System.setProperty("java.class.path",newPath). Though I set the class path, it throws an error.

This is my code:
A.java
class A
{

public static void main(String[] args)
{
System.setProperty("java.class.path","E:\\javadem\\");
System.out.println("prop: "+System.getProperty("java.class.path"));

B obj=new B();
System.out.println("Class A from C directory");
obj.display();
}
}


B.java
class B
{
public void display()
{
System.out.println("B class!!!");
}
public static void main(String[] args)
{
System.out.println("This is class B fom E directory");
}
}

I have another class file in E: directory and I want to access it. How can i set the class path in runtime in java?

What I have tried:

I have tried setting the path in commandline. It worked. But, I want to set it via code.

Error:

A.java:18: error: cannot find symbol
B obj=new B();
^
  symbol:   class B
  location: class A
Posted
Updated 15-Jun-21 22:46pm
v3
Comments
Patrice T 16-Jun-21 3:25am    
And you plan to tell the error message ?
15160877 16-Jun-21 3:30am    
Updated
CHill60 16-Jun-21 3:56am    
Where is your definition of B?
15160877 16-Jun-21 4:40am    
Updated
Richard MacCutchan 16-Jun-21 5:05am    
You could try setting it inside a static anonymous method, so it gets actioned as soon as the class is loaded.

I just tried that and it does not work.

1 solution

If class B is in another file then you need to import it. Follow the instructions here - Calling a class in another file[^]
 
Share this answer
 
Comments
15160877 16-Jun-21 4:51am    
Is there any way of doing this by setting the classpath inside the program?
CHill60 16-Jun-21 5:16am    
The classpath will have already been read, so even if you amend the environment variable within your program it will have no effect

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900