Как да заредите клас, който не е в вашия проект


Примерно “c:\\other_classes\\” не е във вашия проект, ето пример , как да заредим Java клас от тази папка.

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.CodeSource;
import java.security.ProtectionDomain;
 
public class App{
 
	public static void main(String[] args) {
 
	try{
 
		File file = new File("c:\\other_classes\\"); 
 
                //Превръща файла в url формат
		URL url = file.toURI().toURL(); 
		URL[] urls = new URL[]{url}; 
 
                //Зарежда папката в клас
		ClassLoader cl = new URLClassLoader(urls); 
 
                //Зарежда адресът на класа в 'c:\\other_classes\\'
		Class  cls = cl.loadClass("com.mkyong.io.Address");		
 
                //Извежда местоположението, в което е бил класът
		ProtectionDomain pDomain = cls.getProtectionDomain(); 
		CodeSource cSource = pDomain.getCodeSource(); 
		URL urlfrom = cSource.getLocation();
		System.out.println(urlfrom.getFile());
 
	}catch(Exception ex){
		ex.printStackTrace();
	}
  }
}

Бележка:

/c:/other_classes/

Знайте, че класът е зареден от “/c:/other_classes/“, който не е във вашия проект.

Popularity: 1% [?]

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

You can leave a response, or trackback from your own site.

Leave a Reply

Задвижван с помощта на WordPress | Compare Cell Phone Plans at iCellPhonePlans.com | Thanks to Cheap Palm Pixi, Bromoney and Wordpress Themes