简体   繁体   English

编写一个类,以便它可以扩展或传递块JAVA

[英]Writing a class so it can be extended or passing blocks JAVA

For a Java class we are writing Data structure classes and we need to write a tester class to go with them. 对于Java类,我们正在编写数据结构类,我们需要编写一个测试器类来与它们一起使用。 I am going for extra credit and trying to write a single tester class that I could either extend or pass a block to for use for any testing. 我想要额外的功劳,并尝试编写一个单独的测试器类,我可以扩展或传递一个块用于任何测试。

Is it possible to pass a block of code for a method to run? 是否可以传递一个代码块来运行一个方法? If this is not possible or practical, what is the best way to write a class so it can be extended? 如果这不可能或不实用,那么编写一个类以便扩展它的最佳方法是什么?

--CODE-- - 码 -

package Lab1;

/**
 * @author $RMDan
 * @date   10-Sep-2012
 * @class  Tester
 * @desc   A Tester class for testing Java classes
 *         For use in Itec 251
 */

import java.io.*; 
import java.util.*;

public class Tester {

    //members
    private String logS;

    //Constructors
    //Default to start == true

    public Tester(){
        this(true);
    }

    public Tester(Boolean start){
        if(start == true){
            this.start();
        }
    }

    public final int start(){
        int exit;
        exit = test();
        //this.displayLog();
        this.exportLog("Test_Employee.Log");
        return exit;
    }


    //Change the contents of this method to perform the test
    private int test(){

        return 0;
    }

    private void log(String message){
        this.log(message,true);
    }

    private void log(String message, boolean display){
        this.logS += message + "\n";

        if(display==true){
            System.out.println(message);
        }
    }

    private void displayLog(){
        System.out.print(this.logS);
    }

    private void exportLog(String file){

        try{
            String output = this.logS;
            output = output.replaceAll("\n", System.getProperty("line.separator"));
            try (BufferedWriter out = new BufferedWriter(new FileWriter(file + ".txt"))) {
                out.write(output);
            }
        }
        catch(IOException e){
            System.out.println("Exception ");
        }

    }
}

Note: the final in the declaration of the start() method is there to shut up the compiler. 注意:start()方法声明中的final是关闭编译器的。

Overkill time: have a look at JUnit , a test framework used in many real-life applications. 过度杀伤时间:看看JUnit ,这是一个在许多现实应用程序中使用的测试框架。 It is designed to make it easy to implement tests. 它旨在使实现测试变得容易。 A typical test may be as small as this: 典型的测试可能与此一样小:

import org.junit.*;
import org.junit.assert.*;
public class NameOfClassToTest {
    @Test public void nameOfSpecificTest() {
        // logic to calculate 'expected' and 'result'
        // actual example test
        assertTrue(expected.equals(result));
    }
}

And can be command-line executed with this: 并且可以使用以下命令行执行:

java org.junit.runner.JUnitCore TestClass1 [...other test classes...]

(Although your IDE probably includes in-built support for JUnit tests). (尽管您的IDE可能包含对JUnit测试的内置支持)。

As a teacher, I would be much more impressed if you implement a JUnit test than if you build your own testing framework from scratch... 作为一名教师,如果您实施JUnit测试,那么我会比从头开始构建您自己的测试框架更令人印象深刻......

"Passing a block of code" is the same as passing a reference to an object with a known method (ie interface). “传递代码块”与使用已知方法(即接口)传递对象的引用相同。 eg : 例如:

public class Tester {
  public static void testSomeCodeBlock(Runnable codeBlock) {
    codeBlock.run();
  }
}

Tester.testSomeCodeBlock(new Runnable() {
  @Override public void run() {
    System.out.println("my code block");
  }
});

Alternately, if you wanted to use extension, you would have to make your Tester.test() method protected (and probably abstract) so the test implementations could override it. 或者,如果您想使用扩展,则必须使Tester.test()方法受到保护(并且可能是抽象的),以便测试实现可以​​覆盖它。

In java, "passing a block" is done by anonymous classes : on-the-fly implementations of an interface or class. 在java中,“传递块”由匿名类完成:接口或类的即时实现。 You could use an existing interface like Runnable , or create your own interface that returns a value, for example: 您可以使用现有的接口,如Runnable ,或创建自己的返回值的接口,例如:

interface MyTest {
    int test();
}

then alter your code to expect one of these: 然后改变你的代码以期待其中一个:

public final int start(MyTest myTest) {
    ...
    exit = myTest.test();
    ...
}

then to use it anonymously, call your start method with an anonymous MyTest: 然后匿名使用它,用匿名的MyTest调用你的start方法:

start(new MyTest() {
    public int test() {
        // do something
    } 
})l


You will definitely get more points for using anonymous classes! 使用匿名类肯定会获得更多积分!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM