我正在编写一个游戏,其中玩家通过更改关卡中的对象的源代码来导航谜题。为了做到这一点,我有一个扩展JPanel的类,它将使用来自播放器的已编辑源代码进行编写。我的问题是如何使用java实用程序或使用beanshell从文本文件编译类文件?文本文件包含纯java,但游戏的玩家可能会导致编译或运行时错误(例如无限循环),我希望能够捕获所述错误并提醒玩家。
答案 0 :(得分:1)
听起来很棒,但动态编译类并让它们执行需要相当多的工作。有一个名为Janino的库(用他们自己的话说):
Janino是一款超小型超高速Java™编译器。它不仅可以将一组源文件编译为一组类文件(如JAVAC),还可以在内存中编译Java™表达式,块,类主体或源文件,加载字节码并直接在同一JVM中执行
通过将与实际编译和运行动态代码相关的工作委托给Janino,您可以专注于实际的游戏逻辑。
答案 1 :(得分:0)
如果您不想使用外部库,则需要编写自己的ClassLoader。我找到的最简单的实现是here。
/*
* Copyright 2008-2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.btrace;
/**
* A simple class loader that loads from byte buffer.
*
* @author A. Sundararajan
*/
final class MemoryClassLoader extends ClassLoader {
MemoryClassLoader() {
this(null);
}
MemoryClassLoader(ClassLoader parent) {
super(parent);
}
Class loadClass(String className, byte[] buf)
throws ClassNotFoundException {
return defineClass(className, buf, 0, buf.length);
}
}
答案 2 :(得分:0)
您可以考虑使用JVM支持的脚本语言(如Groovy)作为动态部分。