Во время игры с загрузчиками классов я получил следующее исключение:
Exception in thread "main" java.lang.ClassCastException: xxx.Singleton cannot be cast to xxx.Singleton
Означает ли это, что экземпляр загрузчика классов нельзя привести к классу другого загрузчика классов?
Проверьте мой код, в котором я могу создать экземпляр 3 синглтонов благодаря загрузчикам классов, даже с защитой "".
public static void main(String[] args) throws Exception {
URL basePath = new URL("file:/myMavenPath/target/classes/");
Object instance = getClassInstance(Singleton.class);
System.out.println(instance);
//
Object instance2 = getClassInstance(
new URLClassLoader( new URL[]{basePath} , null )
.loadClass("my.Singleton")
);
System.out.println(instance2);
//
Object instance3 = getClassInstance(
new URLClassLoader( new URL[]{basePath} , null )
.loadClass("my.Singleton")
);
System.out.println(instance3);
// Only the 1st cast is ok
Singleton testCast1 = (Singleton) instance;
System.out.println("1st cast ok");
Singleton testCast2 = (Singleton) instance2;
System.out.println("2nd cast ok");
Singleton testCast3 = (Singleton) instance3;
System.out.println("3rd cast ok");
}
private static Object getClassInstance(Class clazz) throws Exception {
Method method = clazz.getMethod("getInstance");
method.setAccessible(true);
return method.invoke(null);
}
class Singleton {
private static final Singleton INSTANCE = new Singleton();
public static Singleton getInstance() {
return INSTANCE;
}
private Singleton() {
Exception e = new Exception();
StackTraceElement[] stackTrace = e.getStackTrace();
if (!"".equals(stackTrace[1].getMethodName())) {
throw new IllegalStateException("You shall not instanciate the Singleton twice !",e);
}
}
public void sayHello() {
System.out.println("Hello World ! " + this);
}
}
Подробнее здесь: https://stackoverflow.com/questions/118 ... assloaders
ClassCastException из-за загрузчиков классов? ⇐ JAVA
Программисты JAVA общаются здесь
-
Anonymous
1731629870
Anonymous
Во время игры с загрузчиками классов я получил следующее исключение:
Exception in thread "main" java.lang.ClassCastException: xxx.Singleton cannot be cast to xxx.Singleton
Означает ли это, что экземпляр загрузчика классов нельзя привести к классу другого загрузчика классов?
Проверьте мой код, в котором я могу создать экземпляр 3 синглтонов благодаря загрузчикам классов, даже с защитой "".
public static void main(String[] args) throws Exception {
URL basePath = new URL("file:/myMavenPath/target/classes/");
Object instance = getClassInstance(Singleton.class);
System.out.println(instance);
//
Object instance2 = getClassInstance(
new URLClassLoader( new URL[]{basePath} , null )
.loadClass("my.Singleton")
);
System.out.println(instance2);
//
Object instance3 = getClassInstance(
new URLClassLoader( new URL[]{basePath} , null )
.loadClass("my.Singleton")
);
System.out.println(instance3);
// Only the 1st cast is ok
Singleton testCast1 = (Singleton) instance;
System.out.println("1st cast ok");
Singleton testCast2 = (Singleton) instance2;
System.out.println("2nd cast ok");
Singleton testCast3 = (Singleton) instance3;
System.out.println("3rd cast ok");
}
private static Object getClassInstance(Class clazz) throws Exception {
Method method = clazz.getMethod("getInstance");
method.setAccessible(true);
return method.invoke(null);
}
class Singleton {
private static final Singleton INSTANCE = new Singleton();
public static Singleton getInstance() {
return INSTANCE;
}
private Singleton() {
Exception e = new Exception();
StackTraceElement[] stackTrace = e.getStackTrace();
if (!"".equals(stackTrace[1].getMethodName())) {
throw new IllegalStateException("You shall not instanciate the Singleton twice !",e);
}
}
public void sayHello() {
System.out.println("Hello World ! " + this);
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/11865917/classcastexception-because-of-classloaders[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия