gpt4 book ai didi

java - 悖论实例化

转载 作者:太空狗 更新时间:2023-10-29 22:44:14 26 4
gpt4 key购买 nike

是否想在不修改类本身的情况下实例化 Paradox 类?

public final class Paradox {
private final Paradox paradox;

public Paradox(Paradox paradox) {
this.paradox = paradox;
if (this.paradox == null) throw new InceptionException();
}

private static class InceptionException extends RuntimeException {
public InceptionException() {
super("Paradox requires an instance of paradox to be instantiated");
}
}
}

最佳答案

正如评论中已经指出的那样:sun.misc.Unsafe 类是可能的:

import java.lang.reflect.Constructor;

import sun.misc.Unsafe;

public class ParadoxTest
{
public static void main(String[] args) throws Exception
{
Constructor<Unsafe> unsafeConstructor =
Unsafe.class.getDeclaredConstructor();
unsafeConstructor.setAccessible(true);
Unsafe unsafe = unsafeConstructor.newInstance();
Paradox paradox = (Paradox) unsafe.allocateInstance(Paradox.class);
System.out.println("This is paradox: "+paradox);
}
}

或者,可以使用 JNI function AllocObject ,它还分配了一个新对象而不调用任何构造函数。

EDIT: Someone found another solution - without sun.misc.Unsafe!

EDIT2: But note that this solution also uses Sun proprietary classes, which are not part of the public API, and so this solution is still not portable and should not be used in production code!

import java.lang.reflect.Constructor;

import sun.reflect.ReflectionFactory;

public class AnotherParadoxTest
{
public static void main(String[] args) throws Exception
{
ReflectionFactory rf = ReflectionFactory.getReflectionFactory();
Constructor<?> declaredConstructor =
Object.class.getDeclaredConstructor();
Constructor<?> constructor = rf.newConstructorForSerialization(
Paradox.class, declaredConstructor);
Paradox paradox = (Paradox) constructor.newInstance();
System.out.println("This is paradox: "+paradox);
}

}

EDIT3: Just for completeness, and per request in the comments: The JNI-based solution

如上所述,JNI function AllocObject不调用构造函数,因此 this 也可用于实例化此类对象。这是包含 native 方法并加载 native 库的调用类:

public class ParadoxTestWithJni
{
static
{
System.loadLibrary("Paradox");
}
public static void main(String[] args)
{
Paradox paradox = createParadox();
System.out.println("This is paradox: "+paradox);
}

private native static Paradox createParadox();
}

使用 javah 为此类创建的 header ParadoxTestWithJni.h:

#include <jni.h>
#ifndef _Included_ParadoxTestWithJni
#define _Included_ParadoxTestWithJni
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT jobject JNICALL Java_ParadoxTestWithJni_createParadox
(JNIEnv *, jclass);
#ifdef __cplusplus
}
#endif
#endif

相应的实现......“魔法发生的地方”:

#include "ParadoxTestWithJni.h"
JNIEXPORT jobject JNICALL Java_ParadoxTestWithJni_createParadox
(JNIEnv *env, jclass c)
{
jclass paradoxClass = env->FindClass("Paradox");
jobject paradox = env->AllocObject(paradoxClass);
return paradox;
}

关于java - 悖论实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32318302/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com