Java utilities to throw checked exceptions in a "sneaky" way.

Overview

Sneaky Java

Java utilities to throw checked exceptions in a "sneaky" way.

If you're tired of checked exceptions in lambdas, then this library is made for you! For example, take a look at this code snippet.

class MyClass {

  void doAction() {
    List<String> messageContents = getStringLines()
        .stream()
        .map(str -> {
          try {
            return objectMapper.readValue(str, MessageDTO.class);
          } catch (JsonProccesingException e) {
            throw new RuntimeException(e);
          }
        })
        .map(msg -> msg.getContent())
        .toList();
  }
}

It can be simplified with Sneaky.function.

class MyClass {

  void doAction() {
    List<String> messageContents = getStringLines()
        .stream()
        .map(Sneaky.function(
            str -> objectMapper.readValue(str, MessageDTO.class)
        ))
        .map(msg -> msg.getContent())
        .toList();
  }
}

This library has no dependencies.

The master branch provides the latest DEV-SNAPSHOT version. You can find the specific release version info by git tags.

Status

Build Status Javadoc Quality Gate Status Coverage Hits-of-Code checkstyle PMD MIT License

Quick Start

You need Java 8+ to use the library.

Please, use the latest release version Maven Central .

Maven:

<dependency>
  <groupId>com.kirekov</groupId>
  <artifactId>sneaky-java</artifactId>
  <version>x.y.z</version>
</dependency>

Gradle:

implementation 'com.kirekov:sneaky-java:x.y.z' 

Usage

The library provides wrappers for native Java functional interfaces.

Suppose we want to declare a Predicate to use it within Stream API. Here we got isValueAllowed method.

class Predicates {

  boolean isValueAllowed(String value) throws IOException {
    // filtering logic  
  }
}

Sadly, the underlined statement won't compile.

class MyService {

  void doJob() {
    // compile error happens here
    Predicate<String> predicate = (value) -> isValueAllowed(value);
    ...
  }
}

Because isValueAllowed may throw IOException which is a checked exception. Whilst Predicate declaration does not allow it. We can write a custom wrapper for this case.

class MyService {

  void doJob() {
    Predicate<String> predicate = (value) -> {
      try {
        return isValueAllowed(value);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
    ...
  }
}

Though the solution it does work, it looks rather ugly. Fortunately, sneaky-java provides convenient factory methods for such cases.

import com.kirekov.sneaky.Sneaky;

class MyService {

  void doJob() {
    Predicate<String> predicate = Sneaky.predicate(
        value -> isValueAllowed(value)
    );
    ...
  }
}

Besides, sneaky predicates does not wrap checked exceptions with RuntimeException instance. Instead, it uses Java generic type erasure mechanism to rethrow checked exception ignoring compile errors. Here is the core idea.

class Sneaky {

  @SuppressWarnings("unchecked")
  public static <T extends Exception> void throwUnchecked(Exception exception) throws T {
    throw (T) exception;
  }
}

The sneaky-java provides wrappers for the common Java functional interfaces.

  1. PredicateSneaky.predicate
  2. BiPredicateSneaky.biPredicate
  3. FunctionSneaky.function
  4. BiFunctionSneaky.biFunction
  5. ConsumerSneaky.consumer
  6. BiConsumerSneaky.biConsumer
  7. SupplierSneaky.supplier
You might also like...

Android Auto Apps Downloader (AAAD) is an app for Android Phones that downloads popular Android Auto 3rd party apps and installs them in the correct way to have them in Android Auto.

Android Auto Apps Downloader (AAAD) is an app for Android Phones that downloads popular Android Auto 3rd party apps and installs them in the correct way to have them in Android Auto.

Android Auto Apps Downloader (AAAD) is an app for Android Phones that downloads popular Android Auto 3rd party apps and installs them in the correct way to have them in Android Auto.

Jan 2, 2023

Some anti afk bot which prevents you from getting punished for going afk in games. Way of stopping the bot is slightly flawed but we'll ignore that.

Some anti afk bot which prevents you from getting punished for going afk in games. Way of stopping the bot is slightly flawed but we'll ignore that.

AntiAFK Some anti afk bot which prevents you from getting punished for going afk in games. Gui mode coming soon... Installation Install Java 17. Downl

Jan 13, 2022

Cadence is a distributed, scalable, durable, and highly available orchestration engine to execute asynchronous long-running business logic in a scalable and resilient way.

Cadence This repo contains the source code of the Cadence server and other tooling including CLI, schema tools, bench and canary. You can implement yo

Jan 4, 2023

Conway's Game Of Life, but made by me in a very inefficient and unpractical way. Still, I am proud!

Conway's Game Of Life, but made by me in a very inefficient and unpractical way. Still, I am proud!

Conway's Game Of Life, but made by me in a very ugly and inefficient way. Still, I am proud! I want to share my appreciation to cellular automata with anyone who comes across this repo.

May 25, 2022

A small companion library to Mixin, designed to help you write your Mixins in a more expressive and compatible way.

MixinExtras A small companion library to Mixin, designed to help you write your Mixins in a more expressive and compatible way. More information about

Jan 7, 2023

This sample shows how to implement two-way text chat over Bluetooth between two Android devices, using all the fundamental Bluetooth API capabilities.

This sample shows how to implement two-way text chat over Bluetooth between two Android devices, using all the fundamental Bluetooth API capabilities.

Zenitsu-Bluetooth Chat Application This sample shows how to implement two-way text chat over Bluetooth between two Android devices, using all the fund

Jan 16, 2022

Rebuilding nand2tetris from scratch in different way - Group Project

nand2tetris Rebuilding nand2tetris from scratch in different way - Group Project License - GNU GPL v2.0 The contents of this file are subject to the G

Apr 2, 2022

Harvest your animals in the most cursed way possible.

Harvest your animals in the most cursed way possible.

Reaping Harvest your animals in the most cursed way possible. By using the Reaper you can harvest food from animals as if you had killed them, but wit

Oct 23, 2022

A fun way to learn Camunda and win a small price

A fun way to learn Camunda and win a small price

Camunda-Coding-Challenge A fun way to learn about Camunda and win a small prize. The coding challenge is designed for the Camunda Code Studio. Results

Oct 2, 2021
Comments
  • API design improvement proposal: overload all methods

    API design improvement proposal: overload all methods

    Found annoying to figure out each time which method to use. I'm not very good at rememebering all Java functional interfaces.

    Proposal:

    Give all Sneaky class methods same name (unchecked for example) thus overloading them. Instead of writing

    myStream.forEach(Sneaky.consumer(lambda));
    

    it would look like

    myStream.forEach(unchecked(lambda));
    

    Notice static import now is more sensible.
    Also it helps with refactoring when lambda signature changes.

    enhancement 
    opened by mleg 2
Owner
Semyon Kirekov
I like to write software that brings benefits to other people.
Semyon Kirekov
Fall is an app that lets your phone scream if you throw it somewhere.

Fall Fall is an app that lets your phone scream if you throw it somewhere. License Copyright (C) 2022 Gh05t-1337 This program is free software: you ca

null 15 Oct 31, 2022
Test case to check if the Log4Shell/CVE-2021-44228 hotfix will raise any unexpected exceptions

Log4Shell Hotfix Side Effect Test Case I wanted to know if any ClassNotFoundException or similar unexpected exception is raised when one applies the C

Malte S. Stretz 3 Nov 9, 2022
"Some" Utilities you can use for your Java projects "freely"! Files are compiled with Java-8 and above, but mostly Java-11.

✨ Java-SomeUtils ?? "Some" Utilities you can use for your Java projects "freely"! *"Freely"* forcing you to include the license into your program. Fil

JumperBot_ 2 Jan 6, 2023
Excel utility for Java to read and write data in declarative way.

Data Excel Exporter A Java wrapper using Apache POI to read and write Excel file in declarative fashion. Installation ExcelUtil is using Apache POI ve

null 27 Oct 16, 2022
Multifunctional bot with moderation, information and utilities commands.

Module Multifunctional bot with moderation, information and utilities commands. Invite, Server. Technologies Java Spring JDA JDA-Chewtils PostgreSQL L

Headcrab 0 Dec 2, 2022
simple ui utilities lib

UiUtilities a custom android libe help to show or hide view as expande row Step 1. Add the JitPack repository to your build file Add it in your root b

Ali Tarek Hrhera 3 Apr 18, 2022
🍀 Utilities for working with the Spigot library

?? VettherUtilities Spigot utilities for versions: 1.14, 1.15, 1.16, 1.17, 1.18 Require Java 11 or higher. Use older versions at your own risk! Featur

Vetther 4 Oct 17, 2022
Discord Bot with many useful utilities!

Utility Discord Bot Discord Bot with many utilities like base64/hex de-/encode and string hashing Invite the bot Does need manage role perms. Its requ

ReisMiner 4 Dec 14, 2022
Lightweight and Necessary utilities for mini minecraft server

WithMyFriends Lightweight server tools for minimal servers. Contributing to us Version Strategy Why? Despite a huge amount of Server Essential Plugins

iceBear 6 Mar 4, 2022
Shitty, yet simple way to get someone's token right at their discord client's startup.

discord-token-stealer Shitty, yet simple discord injector to add a little spice to their discord client Disclaimer: This is for educational purposes o

Gavin 3 Sep 26, 2022