Ne kadar programlı ve bir Java sınıf derleme oluşturmak mı?
Sınıf adı özelliği bir dosya var. Sınıflar deposu İDynamicLoad uygulayacak biliyorum. Nasıl bir sınıf dinamik olarak oluşturmak mı?
Şu anda var
Properties foo = new Properties();
foo.load(new FileInputStream(new File("ClassName.properties")));
String class_name = foo.getProperty("class","DefaultClass");
//IDynamicLoad newClass = Class.forName(class_name).newInstance();
Newİnstance sadece yük derlenmiş .class dosyaları? Nasıl derlenmiş Java Sınıf yük?
CEVAP
Nasıl derlenmiş Java Sınıf yük?
Önce derlemelisiniz. Bu program aracılığıyla javax.tools
API ile yapılabilir. Bu sadece JDK TOTEM üstüne yerel makinede yüklü olması gerekir.
Burada temel başlangıç bir örnek (açık özel durum işleme bir kenara bırakarak):
// Prepare source somehow.
String source = "package test; public class Test { static { System.out.println(\"hello\"); } public Test() { System.out.println(\"world\"); } }";
// Save source in .java file.
File root = new File("/java"); // On Windows running on C:\, this is C:\java.
File sourceFile = new File(root, "test/Test.java");
sourceFile.getParentFile().mkdirs();
Files.write(source, sourceFile, StandardCharsets.UTF_8);
// Compile source file.
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, sourceFile.getPath());
// Load and instantiate compiled class.
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
Class<?> cls = Class.forName("test.Test", true, classLoader); // Should print "hello".
Object instance = cls.newInstance(); // Should print "world".
System.out.println(instance); // Should print "test.Test@hashcode".
Gibi verir
hello
world
test.Test@ab853b
Daha sonra kullanmak bu sınıflar 10* *zaten sınıf içinde belli bir arayüz daha kolay olurdu.
SomeInterface instance = (SomeInterface) cls.newInstance();
Aksi takdirde erişim Reflection API dahil ve (bilinmeyen) yöntemleri/alanları çağırmak gerekir.
Söyledi ve ilgisiz gerçek sorunu için:
properties.load(new FileInputStream(new File("ClassName.properties")));
java.io.File
geçerli çalışma dizini güveniyor bırakmak taşınabilirlik sorun için reçete. Bunu yapma. Sınıf içinde dosya koymak ve sınıf-göreli bir yol ile ClassLoader#getResourceAsStream()
kullanın.
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("ClassName.properties"));
Nasıl&; derleme quot&; Java sınıf dosy...
Nasıl derleme çözülmemiş sorunları ile...
Ne kadar uzak Git bir şube oluşturmak ...
Java iç sınıf ve statik iç içe sınıf...
Nasıl bir dosyanın içeriğini bir Java ...