Home:ALL Converter>How to pass an Arbitrary number of Parameterized Functions into constructor without compiler Warnings

How to pass an Arbitrary number of Parameterized Functions into constructor without compiler Warnings

Ask Time:2022-04-16T07:56:32         Author:h1dden

Json Formatter

I have a Test class and a Writer class.

The Writer class does nothing but writes a string to a StringBuilder, nothing more. It also is allowed to have "transformers". Meaning, in the constructor of the Writer class, you can pass any number of lambda functions to add additional processing to a string you are writing.

For example, like String::toLowerCase.

I want to be able to pass multiple of these "transformers" into the constructor of the writer.

I have the below code:

///Writer Class   Writer(Function<String, String>... someFunctions) {
abstract class Writer {
  Function<String, String>[] functions;

  Writer(Function<String, String>... someFunctions) {
    functions = someFunctions;
  }

}

///Test Class
    @Test
    default void WriterTestWriteThere() throws IOException {
        Writer writer = createWriter();
        writer.write("There");
        writer.close();

        assertEquals("There", getContents());
    }

    @Test
    default void WriterTestTwoTransformerFunctions() throws IOException {
        Writer writer = createWriter(
                text -> text.replaceAll("sometext", "s*****"),
                String::toUpperCase
        );
        writer.write("This is somethext!");
        writer.close();

        assertEquals("THIS IS S*****!", getContents());
    }

However, the compiler issues multiple warnings.

Possible heap pollution from parameterized vararg type - error-message for the constructor of the Writer class.

Unchecked generics array creation for varargs parameter - error-message for the Test class when the Writer instance is being created.

I cannot use @SafeVarargs or @SuppressWarnings

I have looked everywhere online, but cannot get a solid answer as to why these warnings are created, other than that the Java compiler does not like parameterized arguments being passed into a list. So, raises my question.

What can I use to fix it?

I need to be able to pass multiple functions into the writer class to transform the text as those functions want, and have no warnings. I have experimented with other Java utility classes other than Function, but I can't seem to find what I need.

Author:h1dden,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/71889963/how-to-pass-an-arbitrary-number-of-parameterized-functions-into-constructor-with
yy