Java ClassLoader – force reloading already loaded classes

I’m currently trying to load classes into my application so that I can then filter out those that don’t contain any test / @Test-methods. I want to run these tests in my application afterwards.

So far, so good – except it seems like the URLClassLoader I’m using (or probably any ClassLoader) doesn’t actually reload classes that are located on my applications classpath.

More precisely, a user of my application starts by selecting a number of .java source files. Those are then copied to a temporary location and a number of regex match/replace pairs are applied to the copy of the original source files. Next, the copies are compiled, and I then want to load those compiled .class-files into my application so I can run them as tests.
In most cases, this works as desired.

Unfortunately, if the fully qualified class name (FQCN) of any of the selected files is identical to the FQCN of a class that is part of this application (such as tests for this application), the ClassLoader ignores the specified path (to %temp%myfolder) and the (updated) version of the class file located there, but instead uses the already present/loaded version of the class.

After some research, this behaviour can be expected according to the docs (emphasis mine):

• The loadClass method in ClassLoader performs these tasks, in order, when called to load a class:
If a class has already been loaded, it returns it.
– Otherwise, it delegates the search for the new class to the parent class loader.
– If the parent class loader does not find the class, loadClass calls the method findClass to find and load the class.

I tried using findClass, but it’s unfortunately not visible.

Hence my question – does anyone know how to force java / the ClassLoader to actually load the class from the specified path, ignoring any – FQCN-wise – identical existing classes?

Printwriter multiple lines with StringBuilder to CSV-file

I have 100 particles that all move with the help of Timer and ActionListener. I’m tracking the movement of my particles by saving the coordinates x,y in a StringBuilder. When the process is done I’m trying to print the results into a CSV-file, with an output that looks like this;

time1, x1, y1, x2, y2, ... , xn, yn
time2, x1, y1, x2, y2, ... , xn, yn
, At the moment the timer stops after the particles have moved 100 times, I use a counter in my ActionListener to get this done. The problem is, my output in my CSV-file looks all messed up with more than 600 rows, it should only have 100 rows.

I’ve tried using different “newline”-commands like n, rn, %n, but none of them gives me 100 lines.

The reason I want to use a StringBuilderand not just use +is because I want the code to work for as many particles as possible. If you have any other suggestions, I would gladly take them.

Below are the parts of the code I think you might need to understand the problem. If anyone wants/needs more, I can post all the code.

Controller:

public class Controller extends JPanel implements ChangeListener, ActionListener{

    Model model;
    View view;
    private Timer timer;
    private int delta = 100;
    private StringBuilder csv = new StringBuilder();
    private int counter = 0;
    private int time = 2000;

    public Controller(Model m, View v) {
        model = m;
        view = v;
        timer = new Timer(delta, this);
        timer.setInitialDelay(time);
        timer.start();

    public void actionPerformed(ActionEvent arg0) {
        counter++;

        csv.append(time);
        csv.append(model.getPos());
        csv.append("n");

        model.updatePos();
        view.repaint();
        time += delta * 0.001;

        if (counter>100) {
            timer.stop();
            PrintWriter pw;
            try {
                pw = new PrintWriter("data.csv");
                pw.println(csv);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}

Model:

public class Model {

    public int numberofparticles;
    public ArrayList<Particle> particlelist;
    public StringBuilder position = new StringBuilder();

    Model() {
        particlelist = new ArrayList<Particle>();
        numberofparticles = 100;
        for (int i = 0; i < numberofparticles; i++) {
            particlelist.add(new Particle());
        }
    }

    public void updatePos() {
        for (int i = 0; i < numberofparticles; i++) {
        particlelist.get(i).x += 2*Math.cos(Math.random()*2*Math.PI);
        particlelist.get(i).y += 2*Math.sin(Math.random()*2*Math.PI);
        }
    }

    public StringBuilder getPos() {
        for (int i=0; i < numberofparticles; i++) {
            position.append(particlelist.get(i).x);
            position.append(",");
            position.append(particlelist.get(i).y);
            position.append(",");
        }
        return position;
    }

Particle is a nested class in Model. All it does is give the particle a starting coordinate x,y

Java- Why is’nt my code producin the correct results?

I was solving problem 4 of ProjectEuler and couldn’t get it right. This is my code.

public static long reverseNumber(long number){
    long reversed = 0;

    while(number != 0) {
        long digit = number % 10;
        reversed = reversed * 10 + digit;
        number /= 10;
    }
        return reversed;
}

long sum,finalSum=1,revSum;
    for (int i=100;i<1000;i++){
    for (int j=100;j<1000;j++){               
        sum=i*j;
        revSum=reverseNumber(sum);
            if (sum==revSum){
            finalSum=sum;
            }

        }
    }
    System.out.println(finalSum);

This was some code I found online and it worked perfectly.

int maxPalin = -1;
    for (int i = 100; i < 1000; i++) {
        for (int j = 100; j < 1000; j++) {
        int prod = i * j;
        if (prod > maxPalin){
                if (reverseNumber(prod)>maxPalin) {
                    maxPalin = prod;
                }
        }
        }
    }
System.out.println(Integer.toString(maxPalin));

But whats wrong with mine?

Hazelcast – Why entryprocessors are not using Portable?

I need to implement cross platform map using portable serialization

I need to insert / update too many values so I use Entryprocessor for insert or update as shown below:

 @Override
 public Object process(Entry<String, Value> entry) {
      if (null == entry.getValue()) {
            //do insert
      } else {
            //do update

      }

      return entry.getValue();
 }

MyEntryProcessor implements Portable .. When there is one hazelcast member there is no problem. When I send elements for processing using hzlMap.executeOnKeys() no error occurs.

But when there are more members I get the below exception from members..

Exception in thread "main" com.hazelcast.nio.serialization.HazelcastSerializationException: Failed to serialize 'com.hazelcast.spi.impl.operationservice.impl.operations.Backup'
    at com.hazelcast.internal.serialization.impl.SerializationUtil.handleSerializeException(SerializationUtil.java:75)
    at com.hazelcast.internal.serialization.impl.AbstractSerializationService.toBytes(AbstractSerializationService.java:155)
    at com.hazelcast.internal.serialization.impl.AbstractSerializationService.toBytes(AbstractSerializationService.java:128)
    at com.hazelcast.spi.impl.operationservice.impl.OutboundOperationHandler.send(OutboundOperationHandler.java:51)
    at com.hazelcast.spi.impl.operationservice.impl.OperationBackupHandler.sendSingleBackup(OperationBackupHandler.java:217)
    at com.hazelcast.spi.impl.operationservice.impl.OperationBackupHandler.makeBackups(OperationBackupHandler.java:189)
    at com.hazelcast.spi.impl.operationservice.impl.OperationBackupHandler.sendBackups0(OperationBackupHandler.java:108)
    at com.hazelcast.spi.impl.operationservice.impl.OperationBackupHandler.sendBackups(OperationBackupHandler.java:74)
    at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.handleResponse(OperationRunnerImpl.java:272)
    at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:195)
    at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.process(OperationThread.java:120)
    at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.run(OperationThread.java:100)
    at ------ submitted from ------.(Unknown Source)
    at com.hazelcast.spi.impl.operationservice.impl.InvocationFuture.resolve(InvocationFuture.java:127)
    at com.hazelcast.spi.impl.operationservice.impl.InvocationFuture.resolveAndThrowIfException(InvocationFuture.java:79)
    at com.hazelcast.spi.impl.AbstractInvocationFuture.get(AbstractInvocationFuture.java:155)
    at com.hazelcast.spi.impl.operationservice.impl.InvokeOnPartitions.retryFailedPartitions(InvokeOnPartitions.java:144)
    at com.hazelcast.spi.impl.operationservice.impl.InvokeOnPartitions.invoke(InvokeOnPartitions.java:74)
    at com.hazelcast.spi.impl.operationservice.impl.OperationServiceImpl.invokeOnPartitions(OperationServiceImpl.java:402)

Hazelcast is trying to serialize MyEntryProcessor using default serialization although it implements Portable?

Why is this happening? Am I missing sth?

How can it be corrected?

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 5921 path $.data[5].courier.data

I have this model object Courier :

public class Courier {
    @SerializedName("data")
    private List<User> data = null;

    public Courier() {
    }

    public Courier(List<User> data) {
        this.data = data;
    }

    public List<User> getData() {
        return data;
    }

    public void setData(List<User> data) {
        this.data = data;
    }
}

I get this response from server:

{
    "data": [
        {
            "id": 446,
            "courier": {
                "data": []
            },
            "title": "гром",
            "description": "Логойский тракт 24 в России в начале следующей",
            "departure": "ChIJPQKUckNv2UYRLr1NasgXZ08",
            "arrival": "EkHQodC10YDQtdCx0YDRj9C90YvQuSDQv9C10YDQtdGD0LvQvtC6LCDQnNC-0YHQutCy0LAsINCg0L7RgdGB0LjRjw"
        },
        {
            "id": 438,
            "courier": {
                "data": []
            },
            "title": "тест",
            "description": "гппг лмш ш ш ш ш г У меня на сковородке стоит ли брать сва в кино мы все равно обсуждаем",
            "departure": "ChIJH10nmDnP20YR-n7Kq6Whd5w",
            "arrival": "Ej_QnNC-0YHQutCy0L7RgNC10YbQutCw0Y8g0YPQu9C40YbQsCwg0JzQvtGB0LrQstCwLCDQoNC-0YHRgdC40Y8"
        },
        {
            "id": 439,
            "courier": {
                "data": []
            },
            "title": "лаьаьаат",
            "description": "лала слат алс ал ала ал кща да аьад",
            "departure": "ChIJH7D4cTnP20YRKlzSCnP6Mak",
            "arrival": "Ej_QnNC-0YHQutCy0L7RgNC10YbQutCw0Y8g0YPQu9C40YbQsCwg0JzQvtGB0LrQstCwLCDQoNC-0YHRgdC40Y8"
        },
        {
            "id": 442,
            "courier": {
                "data": {
                    "id": 122,
                    "email": null,
                    "phone": "73339999999",
                    "photo": null,
                    "rating": 0
                }
            },
            "title": "картошечка",
            "description": "Крупная сортированная",
            "departure": "ChIJnZRv1jnP20YRWiezW55d1tA",
            "arrival": "ChIJpfH6UJtp1EYRlhM20g-jzF4"
        }
    ]
}

If object courier not have data, i get array "data": [], if object courier has data, i get object :

"courier": {
                "data": {
                    "id": 122,
                    "email": null,
                    "phone": "73339999999",
                    "photo": null,
                    "rating": 0
                }
            }

And then I get error… Please give me advice how handle this case in android application…

Spring validation for optional request body

I use Java and Spring to create a post rest webservice. The service obviously has a request body, but it is declared as optional. If the request body is not supplied, the service expects a single query parameter to be supplied instead.

  • POST services/items with a request body will result in a new item to
    be created.
  • POST services/items?copyFromItem=123 without a request
    body will create a new item which is a copy of item 123.

I use spring’s @Valid annotation to valid the request body. The problem is that I want to allow the request body to be null/empty (in the copy item case) but unfortunately then I get validation errors. I cannot remove the @Valid annotation because in that case the body no longer gets validated when it IS supplied.

Here is the code snippet:

@PostMapping()
public CreateItemResponse createItem(
        @Valid @RequestBody(required = false) CreateItemRequest createItemRequest,
        @RequestParam(required = false) Long copyFromItem,
        final BindingResult bindingResult
){

   ...
}