Get Class Annotations from Java Source File - java

I'm parsing Java Source Files to collect various informations about my classes. Therefore I'm using the JavaParser, since I could not find a good alternative (good suggestions have the chance to become "answers") to parse Source Files.
I already managed to get Annotations of all methods from my class. The code looks like this:
package de.mackaz;
import japa.parser.JavaParser;
import japa.parser.ParseException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.body.MethodDeclaration;
import japa.parser.ast.expr.AnnotationExpr;
import japa.parser.ast.expr.MarkerAnnotationExpr;
import japa.parser.ast.expr.MemberValuePair;
import japa.parser.ast.expr.NormalAnnotationExpr;
import japa.parser.ast.visitor.VoidVisitorAdapter;
import java.io.FileInputStream;
public class JavaSourceUtils {
public static void main(String[] args) throws Exception {
File f = new File("/home/mackaz/SourceFile.java");
inspectJavaFile(f);
}
public static void inspectJavaFile(File pFile)
throws FileNotFoundException, ParseException, IOException {
CompilationUnit cu;
FileInputStream in = new FileInputStream(pFile);
try {
cu = JavaParser.parse(in);
} finally {
in.close();
}
new MethodVisitor().visit(cu, null);
}
/**
* Simple visitor implementation for visiting MethodDeclaration nodes.
*/
private static class MethodVisitor extends VoidVisitorAdapter {
#Override
public void visit(MethodDeclaration n, Object arg) {
System.out.println(n.getName());
if (n.getAnnotations() != null) {
for (AnnotationExpr annotation : n.getAnnotations()) {
System.out.println(annotation.getClass());
// MarkerAnnotations, for example #Test
if (annotation.getClass().equals(MarkerAnnotationExpr.class)) {
System.out.println("MarkerAnnotation:" + ((MarkerAnnotationExpr)annotation).getName());
}
if (annotation.getClass().equals(NormalAnnotationExpr.class)) {
for (MemberValuePair pair : ((NormalAnnotationExpr)annotation).getPairs()) {
if (pair.getName().equals("groups"))
System.out.println("Group:\"" + pair.getValue() + "\"");
}
}
}
}
}
}
}
Now how can I get the Annotations of the class itself?

You are overriding public void visit(MethodDeclaration n, Object arg), which visits methods. You can also override public void visit(ClassOrInterfaceDeclaration n, A arg) or public void visit(ClassOrInterfaceType n, A arg), which should give you access to the information you are looking for.

This is how I solved it in the end - I added another Visitor "ClassVisitor":
private static class ClassVisitor extends VoidVisitorAdapter {
#Override
public void visit(ClassOrInterfaceDeclaration n, Object arg) {
for (AnnotationExpr ann: n.getAnnotations()) {
System.out.println(ann.toString());
}
}
}

Looks like you need extend ModifierVisitorAdapter and implement
public Node visit(ClassOrInterfaceDeclaration n, A arg) {
Look at the implementation here for an idea of what you might want to do:
public Node visit(ClassOrInterfaceDeclaration n, A arg) {
if (n.getJavaDoc() != null) {
n.setJavaDoc((JavadocComment) n.getJavaDoc().accept(this, arg));
}
List<AnnotationExpr> annotations = n.getAnnotations();
if (annotations != null) {
for (int i = 0; i < annotations.size(); i++) {
annotations.set(i, (AnnotationExpr) annotations.get(i).accept(this, arg));
}
removeNulls(annotations);
}
List<TypeParameter> typeParameters = n.getTypeParameters();
if (typeParameters != null) {
for (int i = 0; i < typeParameters.size(); i++) {
typeParameters.set(i, (TypeParameter) typeParameters.get(i).accept(this, arg));
}
removeNulls(typeParameters);
}
List<ClassOrInterfaceType> extendz = n.getExtends();
if (extendz != null) {
for (int i = 0; i < extendz.size(); i++) {
extendz.set(i, (ClassOrInterfaceType) extendz.get(i).accept(this, arg));
}
removeNulls(extendz);
}
List<ClassOrInterfaceType> implementz = n.getImplements();
if (implementz != null) {
for (int i = 0; i < implementz.size(); i++) {
implementz.set(i, (ClassOrInterfaceType) implementz.get(i).accept(this, arg));
}
removeNulls(implementz);
}
List<BodyDeclaration> members = n.getMembers();
if (members != null) {
for (int i = 0; i < members.size(); i++) {
members.set(i, (BodyDeclaration) members.get(i).accept(this, arg));
}
removeNulls(members);
}
return n;
}

Related

How to control test execution result in Junit5?

I created a new annotation in JUnit5, that creates a stream of replication of the same test, and runs them or disables them according to some conditions.
But, if at least one of the iterations fails it automatically fails the whole test suite, and I want to be able to control the parent test execution result.
For example, I want to set that if a certain number of replicas have passed then the whole suite should pass.
Is there any way to do this?
Here is my code:
public class Test {
private static int i = 0;
#FlakyTest(maxIterations = 10, maxFailuresRate = 0.4)
public void test() {
if(i++ == 0){
assert false;
} else {
assert true;
}
}
}
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Target({ElementType.METHOD, ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#TestTemplate
#ExtendWith(FlakyTestRunner.class)
public #interface FlakyTest {
int maxIterations() default 6;
double maxFailuresRate() default 0.2;
}
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.Extension;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestTemplateInvocationContext;
import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static flaky.FlakyTestRunner.didPassedFailureRate;
import static org.junit.platform.commons.util.AnnotationUtils.isAnnotated;
public class FlakyTestRunner implements TestTemplateInvocationContextProvider, AfterTestExecutionCallback {
public static int iteration = 0;
public static int maxIterations;
public static double maxFailuresRate;
private static Map<Integer, Boolean> iterationsResultsMap = new HashMap<>();
#Override
public boolean supportsTestTemplate(ExtensionContext extensionContext) {
return isAnnotated(extensionContext.getTestMethod(), FlakyTest.class);
}
#Override
public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(ExtensionContext extensionContext) {
maxIterations = extensionContext.getElement().get().getAnnotation(FlakyTest.class).maxIterations();
maxFailuresRate = extensionContext.getElement().get().getAnnotation(FlakyTest.class).maxFailuresRate();
List invocationContexts = new ArrayList<TestTemplateInvocationContext>();
for (int i = 0; i < maxIterations; i++) {
invocationContexts.add(new FlakyIterationRunnerTemplateInvocationContext());
}
return invocationContexts.stream();
}
#Override
public void afterTestExecution(ExtensionContext extensionContext) {
iterationsResultsMap.put(iteration, !extensionContext.getExecutionException().isPresent());
}
public static boolean didPassedFailureRate() {
if (iteration > 2) {
return getFailedTestsRate() >= maxFailuresRate;
}
return false;
}
private static double getFailedTestsRate() {
int sum = iterationsResultsMap.values()
.stream()
.mapToInt(successFlag -> successFlag ? 0 : 1)
.sum();
return ((double) sum) / maxIterations;
}
}
class FlakyIterationRunnerTemplateInvocationContext implements TestTemplateInvocationContext {
#Override
public List<Extension> getAdditionalExtensions() {
List<Extension> extensions = new ArrayList<>();
extensions.add(new FlakyIterationRunnerExecutionCondition());
return extensions;
}
}
class FlakyIterationRunnerExecutionCondition implements ExecutionCondition {
#Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) {
FlakyTestRunner.iteration++;
if (FlakyTestRunner.iteration <= FlakyTestRunner.maxIterations && !didPassedFailureRate()) {
return ConditionEvaluationResult.enabled("Passed");
}
return ConditionEvaluationResult.disabled("Iteration number: " + FlakyTestRunner.iteration + ", did passed failure rate? " + didPassedFailureRate()
+ ". Max failures rate allowed - " + FlakyTestRunner.maxFailuresRate);
}
}
I generally think "flakey tests" are a bad idea and some level of refactoring can nearly always be done to remove the need for things like this. However if this is the approach you want to take I think you can implement it by having your extension implement TestExecutionExceptionHandler so that you can decide when the AssertionError should cause test failure. I don't know if this is a particularly good implementation but I guess this would do what you want it to:
public class FlakyTestRunner implements TestTemplateInvocationContextProvider, TestExecutionExceptionHandler {
private Map<Method,MultiIterationResult> results = new HashMap<>();
#Override
public boolean supportsTestTemplate(ExtensionContext extensionContext) {
return isAnnotated(extensionContext.getTestMethod(), FlakyTest.class);
}
#Override
public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(
ExtensionContext extensionContext) {
int maxIterations = extensionContext.getElement().get().getAnnotation(FlakyTest.class).maxIterations();
double maxFailuresRate = extensionContext.getElement().get().getAnnotation(FlakyTest.class).maxFailuresRate();
results.put(extensionContext.getTestMethod().get(), new MultiIterationResult(maxIterations, maxFailuresRate));
List invocationContexts = new ArrayList<TestTemplateInvocationContext>();
for (int i = 0; i < maxIterations; i++) {
invocationContexts.add(new FlakyIterationRunnerTemplateInvocationContext());
}
return invocationContexts.stream();
}
#Override
public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
results.get(context.getTestMethod().orElseThrow(() -> throwable)).handleFailure(throwable);
}
private class MultiIterationResult {
private final int iterations;
private final double failureThreshold;
private int failCount = 0;
public MultiIterationResult(int iterations, double failureThreshold) {
this.iterations = iterations;
this.failureThreshold = failureThreshold;
}
public void handleFailure(Throwable throwable) throws Throwable {
failCount++;
if((double)failCount/iterations > failureThreshold) {
throw throwable;
}
}
}
private class FlakyIterationRunnerTemplateInvocationContext implements TestTemplateInvocationContext {
}
}

"The method from ... is never used locally" on a public method inside an anonymous class

I'm implementing the iterable interface and returning the iterator using anonymous class.
The problem is I can't use my custom add from the anonymous class in the main method.
I can't call the add method in the main method.
Eclipse complains that it's not defined.
What is the problem?
I'll spare from you the outer class and just show you the method iterator:
#Override
public Iterator<Symbol> iterator() {
return new Iterator<Symbol>() {
int i = 0; //Remove i and it works. WHY?!!
public boolean hasNext() {
return i < symArr.length && symArr[i] != null;
}
public Symbol next() {
if (hasNext()) {
return symArr[i++];
}
return null;
}
public void add(Symbol addMe) {
if (i < symArr.length) {
symArr[i] = addMe;
}
}
};
}
My main method inside the outer class:
public static void main(String[] args) {
SymbolTable st = new SymbolTable(22);
Iterator<Symbol> it = st.iterator();
it.next();
it.add(new Symbol("2", 2)); //Have problem here.
//Problem disappears when I completely remove i variable in the iterator method.
}
The whole code:
package tirgul_iteratorsExceptions;
import java.util.Iterator;
public class SymbolTable implements Iterable<Symbol> {
Symbol[] symArr;
public SymbolTable(int size) {
symArr = new Symbol[size];
}
public SymbolTable(SymbolTable st, boolean isDeep) {
symArr = new Symbol[st.symArr.length];
if (isDeep) {
for (int i = 0; i < st.symArr.length; i++) {
symArr[i] = new Symbol(st.symArr[i].name, st.symArr[i].value);
}
}
// Shallow copy
else {
for (int i = 0; i < st.symArr.length; i++) {
symArr[i] = st.symArr[i];
}
}
}
#Override
public Iterator<Symbol> iterator() {
return new Iterator<Symbol>() {
int i = 0;
public boolean hasNext() {
return i < symArr.length && symArr[i] != null;
}
public Symbol next() {
if (hasNext()) {
return symArr[i++];
}
return null;
}
public void add(Symbol addMe) {
if (i < symArr.length) {
symArr[i] = addMe;
}
}
};
}
public static void main(String[] args) {
SymbolTable st = new SymbolTable(22);
Iterator<Symbol> it = st.iterator();
it.next();
it.add(new Symbol("2", 2));
}
}

Error: Could not find or load main class ClassDemo

The code below compiled successfully here https://www.compilejava.net/ but execution fails
Error: Could not find or load main class ClassDemo
whereas it does have a main entry point. Why ?
package com.tutorialspoint;
import java.lang.reflect.*;
public class ClassDemo {
public static void main(String[] args) {
try {
ClassDemo c = new ClassDemo();
Class cls = c.getClass();
// returns the array of Field objects
Field[] fields = cls.getDeclaredFields();
for(int i = 0; i < fields.length; i++) {
System.out.println("Field = " + fields[i].toString());
}
}
catch(Exception e) {
System.out.println(e.toString());
}
}
public ClassDemo() {
// no argument constructor
}
public ClassDemo(long l, int i) {
this.l = l;
this.i = i;
}
long l = 77688;
int i = 3;
}
You need to remove the package identifier from your code (first line) since you are using an online compiler/executor.
Hope this helps.
It's because you have a package statement.
Remove that and it will work just fine.

Assistance Required, Developing Java Based Scripting Language?

I have just begun working on a programming language called XScript. It is designed so that I can run it from a Java application, but also re-program it through a java application. The idea being so that I can create virtual computers in games or a program that develops itself over time. So far I have the following code. I understand there may need to be an alteration to the name due to proprietary software, but for now it is fine.
The Artificial Main Class:
import com.x.lang.XLoader;
public class Main {
public static void main(String[] args) {
XLoader xl = new XLoader();
xl.exec("/Users/Nathan/Desktop/XScript/test.xls");
}
}
The XLoader (Loads and executes the XScript):
package com.x.lang;
import java.io.File;
import com.x.lang.object.XObject;
public class XLoader {
XObject xo;
public String fileLocation;
public void exec(String fl) {
fileLocation = fl;
XObject xo = new XObject(new File(fileLocation));
xo.exec();
}
}
The XCommandHub Where the Language Key Functions are Stored:
package com.x.lang;
import com.x.lang.keyword.Print;
import com.x.lang.keyword.Set;
import com.x.lang.object.XCommand;
import com.x.lang.object.XObject;
public class XCommandHub {
public XCommand xc[] = new XCommand[2];
public XCommandHub(XObject x) {
xc[0] = new Print(x);
xc[1] = new Set(x);
}
public XCommand getCommand(String s) {
for (int i = 0; i < 2; i++) {
if (xc[i].getCommandName() == s) {
return xc[i];
}
}
return null;
}
}
The XCommand Class Defining The Keywords:
package com.x.lang.object;
public abstract class XCommand {
private String commandName;
public XObject xobject;
public XCommand (String cn, XObject x) {
commandName = cn;
commandName += ": ";
xobject = x;
}
public abstract void exec(XVar xv);
public String getCommandName() {
return commandName;
}
}
The XVar Class Defining All Variables:
package com.x.lang.object;
public class XVar {
private String var1;
public String name;
public XVar(String s) {
var1 = s;
}
public String getStringValue() {
if (this.var1 != null) {
return var1;
}
return " ";
}
public int getIntValue() {
if (this.var1 != null) {
return Integer.parseInt(var1);
}
return 0;
}
public void setName(String s) {
name = s;
}
}
The XObject Class Actual Executing the Commands:
package com.x.lang.object;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import com.x.lang.XCommandHub;
public class XObject {
public XVar xvars[] = new XVar[150];
public int varCount = 0;
public File f;
XCommandHub x;
public XObject (File file) {
f = file;
x = new XCommandHub(this);
}
public void addVar(XVar var, String name) {
xvars[varCount] = var;
xvars[varCount].setName(name);
varCount++;
}
public XVar getVar(String varName) {
for (int i = 0; i < varCount; i++) {
if (xvars[i].name == varName) {
return xvars[i];
}
}
return null;
}
public void exec() {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
for (int i = 0; i < 2; i++) {
if (sCurrentLine.startsWith(x.xc[i].getCommandName()))
try {
x.getCommand(x.xc[i].getCommandName()).exec(new XVar(sCurrentLine.split(": ")[1]));
} catch (ArrayIndexOutOfBoundsException e) {
x.getCommand(x.xc[i].getCommandName()).exec(new XVar(" "));
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
The Two Classes Defining The Commands I Have Programmed So Far:
package com.x.lang.keyword;
import com.x.lang.object.XCommand;
import com.x.lang.object.XObject;
import com.x.lang.object.XVar;
public class Print extends XCommand {
public Print(XObject x) {
super("print", x);
}
#Override
public void exec(XVar xv) {
if (xv.getStringValue().startsWith("%")) {
try {
System.out.println(xobject.getVar(xv.getStringValue().substring(1)).getStringValue());
} catch (NullPointerException e) {
System.out.println(xv.getStringValue());
}
}
else {
System.out.println(xv.getStringValue());
}
}
}
package com.x.lang.keyword;
import com.x.lang.object.XCommand;
import com.x.lang.object.XObject;
import com.x.lang.object.XVar;
public class Set extends XCommand {
public Set(XObject x) {
super("set", x);
}
#Override
public void exec(XVar xv) {
String[] add = xv.getStringValue().split("=");
xobject.addVar(new XVar(add[1]), add[0]);
}
}
From what I have programmed so far I have tried to give the user the ability to print a variable that they have declared in the code. A basic .xls (X Language Script) might look something like this:
set: x=Hello StackOverflow
print: This was programmed in XScript!
print:
print: %x
However, there is a NullPointerException in the print class when I try and retrieve the variable x from the array. The program returns "%x" rather than "Hello StackOverflow", because I have deliberately caught the exception, however I do not know how it came about in the first place.
Thanks
Doctor_N
Your code will never find the variable it is looking for:
public XVar getVar(String varName) {
for (int i = 0; i < varCount; i++) {
if (xvars[i].name == varName) {
return xvars[i];
}
}
return null;
}
This function will almost always return null since you are comparing strings using == and not using .equals. == compares references (memory addresses) and it is highly unlikely that the parameter and the string you are comparing against will point to the same location. Due to this, you almost always return null.
Because of that, this line will always cause a NullPointerException:
System.out.println(xobject.getVar(xv.getStringValue().substring(1)).getStringValue());
This is because you are effectively calling getStringValue() on null.
I suggest changing the if to:
if(xvars[i] != null && xvars[i].name.equals(varName)) {
...
}

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;

I'm using Eclipse and I'm using Java. My objective it's to sort a vector, with the bogoSort method
in one vector( vectorExample ) adapted to my type of vector and use the Java sort on other vector (javaVector) and compare them.
I did the tests but it did't work, so I don't know what is failing.
*Note: there are few words in spanish: ordenado = sorted, Ejemplo = Example, maximo = maximun, contenido = content.
EjemploVector class
package vector;
import java.util.NoSuchElementException;
import java.util.Vector;
import java.util.Iterator;
public class EjemploVector <T> {
protected T[] contenido;
private int numeroElementos;
#SuppressWarnings("unchecked")
public EjemploVector () {
contenido = (T[]) new Object[100];
numeroElementos = 0;
}
#SuppressWarnings("unchecked")
public EjemploVector (int maximo) {
contenido = (T[]) new Object[maximo];
numeroElementos = 0;
}
public String toString(){
String toString="[";
for (int k=0; k<numeroElementos;k++){
if (k==numeroElementos-1){
toString = toString + contenido[k].toString();
} else {
toString = toString + contenido[k].toString()+", ";
}
}
toString = toString + "]";
return toString;
}
public boolean equals (Object derecho){
if (!(derecho instanceof Vector<?>)) {
return false;
} else if (numeroElementos != ((Vector<?>)derecho).size()) {
return false;
} else {
Iterator<?> elemento = ((Vector<?>)derecho).iterator();
for (int k=0; k<numeroElementos;k++){
if (!((contenido[k]).equals (elemento.next()))) {
return false;
}
}
return true;
}
}
public void addElement (T elemento){
contenido[numeroElementos++]= elemento;
}
protected T[] getContenido(){
return this.contenido;
}
protected T getContenido (int k){
return this.contenido[k];
}
#SuppressWarnings("unchecked")
protected void setContenido (int k, Object elemento){
this.contenido[k]= (T)elemento;
}
EjemploVectorOrdenadoClass
package vector.ordenado;
import java.util.Arrays;
import java.util.Random;
import vector.EjemploVector;
public class EjemploVectorOrdenado<T extends Comparable<T>> extends EjemploVector<T> {
private boolean organized;
public EjemploVectorOrdenado() {
super();
organized = true;
}
public EjemploVectorOrdenado(int maximo) {
super(maximo);
organized = true; //
}
public boolean getOrdenado() {
return this.organized;
}
// Method bogoSort
public void bogoSort() {
if (!this.organized) {
if (this.size() > 0) {
Random generator;
T tempVariable;
int randomPosition;
do {
generator = new Random();
for (int i = 0; i < this.size(); i++) {
randomPosition = generator.nextInt(this.size());
tempVariable = contenido[i];
contenido[i] = contenido[randomPosition];
contenido[randomPosition] = tempVariable;
}
} while (!organized);
}
}
this.organized = true;
}
public void addElement(T elemento) {
super.addElement(elemento);
if (organized && this.size() > 1) {
T penultimo = this.getContenido(this.size() - 2);
T ultimo = this.getContenido(this.size() - 1);
organized = penultimo.compareTo(ultimo) <= 0;
}
}
}
ElementoTest class
package elementos;
import java.io.Serializable;
public class ElementoTest implements Comparable<ElementoTest>, Serializable {
private static final long serialVersionUID = -7683744298261205956L;
private static int numeroElementosTest = 0;
private int clave;
private int valor;
public ElementoTest(int i){
this.clave = i;
this.valor = numeroElementosTest;
numeroElementosTest++;
}
public String toString(){
return ("(" + this.clave + "," + this.valor + ")");
}
public boolean equals (Object derecho){
if (!(derecho instanceof ElementoTest)) {
return false;
} else {
return clave == ((ElementoTest)derecho).clave;
}
}
public char getClave(){
return this.clave;
}
public int getValor(){
return this.valor;
}
#Override
public int compareTo(ElementoTest elemento) {
if (elemento == null){
return -1;
} else if (this.equals(elemento)){
return 0;
} else if (clave < elemento.clave){
return -1;
} else {
return 1;
}
}
}
TESTS
The first it's a stupid test, because it puts elements in order so... really the methods arenĀ“t doing anything, java just compare and it gives correct
I tried to make an unsorted vector adding elements but there appears the java.lang.ClassCastException: [Ljava.... etc.
package vector.ordenado;
import static org.junit.Assert.*;
import java.util.Collections;
import java.util.Vector;
import org.junit.Before;
import org.junit.Test;
import elementos.ElementoTest;
public class EjemploVectorOrdenadoTest {
private Vector<ElementoTest> vectorJava;
private EjemploVectorOrdenado<ElementoTest> vectorExample;
#Before
public void setUp() throws Exception {
vectorJava = new Vector<ElementoTest>(100);
vectorExample = new EjemploVectorOrdenado<ElementoTest>(100);
}
#Test
public void testSortFailTest() {
for (char c = 'a'; c < 'g'; c++) {
vectorJava.addElement(new ElementoTest(c));
vectorExample.addElement(new ElementoTest(c));
}
Collections.sort(vectorJava);
vectorExample.bogoSort();
assertTrue(vectorExample.equals(vectorJava));
assertTrue(vectorExample.getOrdenado());
}
#Test
public void testSort() {
{
vectorJava.addElement(new ElementoTest(1));
vectorJava.addElement(new ElementoTest(3));
vectorJava.addElement(new ElementoTest(2));
vectorExample.addElement(new ElementoTest(3));
vectorExample.addElement(new ElementoTest(2));
vectorExample.addElement(new ElementoTest(1));
}
Collections.sort(vectorJava);
vectorExample.bogoSort();
assertTrue(vectorExample.equals(vectorJava));
assertTrue(vectorExample.getOrdenado());
}
}
Sorry, for the problems and thanks.
The problem is that your test class ElementoTest should implement the Comparable interface. Or you need to provide a Comparator during your comparison.
Does your class ElementtoTest implement Comparable?
If not, it needs to.
I'm suspecting it doesn't, because that's exactly what would cause this error. you'll need to add implements Comparable and then override the int compareTo(Elementtotest e) method, where you specify what criteria you'd like to order the objects based on.

Categories

Resources