Java 从.txt文件编译.class文件

Java 从.txt文件编译.class文件,java,compilation,Java,Compilation,我正在编写一个游戏,玩家通过更改关卡中对象的源代码来导航谜题。为了做到这一点,我有一个扩展JPanel的类,该类将使用播放器编辑的源代码编写。我的问题是如何使用java实用程序或beanshell从文本文件编译类文件?文本文件包含纯java,但游戏玩家可能会导致编译或运行时错误(如无限循环),我希望能够捕获所述错误并提醒玩家 听起来是个好主意,但是动态编译类并让它们执行需要大量的工作。有一个图书馆叫做(用他们自己的话来说): Janino是一个超小型、超快速的Java™ 编译器。它不仅可以将一组

我正在编写一个游戏,玩家通过更改关卡中对象的源代码来导航谜题。为了做到这一点,我有一个扩展JPanel的类,该类将使用播放器编辑的源代码编写。我的问题是如何使用java实用程序或beanshell从文本文件编译类文件?文本文件包含纯java,但游戏玩家可能会导致编译或运行时错误(如无限循环),我希望能够捕获所述错误并提醒玩家

听起来是个好主意,但是动态编译类并让它们执行需要大量的工作。有一个图书馆叫做(用他们自己的话来说):

Janino是一个超小型、超快速的Java™ 编译器。它不仅可以将一组源文件编译成一组类文件,比如JAVAC,还可以编译一个Java™ 表达式、块、类主体或内存中的源文件,加载字节码并直接在同一JVM中执行


通过将与实际编译和运行动态代码相关的工作委托给Janino,您可以专注于实际的游戏逻辑

如果不想使用外部库,则需要编写自己的类加载器。我发现的最简单的实现是


您可以考虑使用JVM支持的脚本语言,如GROOVY作为动态部分。

是否意味着从.txt文件生成.class文件?我将研究Java编译器API。我将研究如下内容:为了捕获运行时错误,如无限循环,当运行用户代码时,使用计时器线程。如果线程超过
x
秒,杀死它,然后抛出超时异常。@SaviourSelf谢谢,计时器工作得很好,我唯一的问题是,什么样的计数可以作为抛出错误的限制?@SDsilver有一些在线编程挑战,比如UVa online Judge,它使用超时来设置代码在被判定错误之前可以运行多长时间的限制。我见过从1秒到5秒的限制,但这需要通过循环、激活帧等进行数十万次迭代。。。如果线程在
x
秒后仍然存在,则抛出它。问题是谁在运行代码。如果它在本地运行,您可能需要一个用户设置变量,以便在运行速度非常慢的系统时可以对其进行更改。答案取决于它们运行的源类型。我无意中点击了“提交”,它应该已完成now@SDsilver是的,这是一个很棒的小图书馆。很高兴我能帮忙。
/*
 * 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);
    }
}