How to get the Array Class for a given Class in Java?

Since Java 12 Class provides a method arrayType(), which returns the array type class whose component type is described by the given Class. Please be aware that the individual JDK may still create an instance of that Class³. Class<?> stringArrayClass = FooBar.arrayType() Before Java 12 If you don’t want to create an instance, you could … Read more

Check if a generic T implements an interface

Generics, oddly enough, use extends for interfaces as well.1 You’ll want to use: public class Foo<T extends SomeInterface>{ //use T as you wish } This is actually a requirement for the implementation, not a true/false check. For a true/false check, use unbounded generics(class Foo<T>{) and make sure you obtain a Class<T> so you have a … Read more

‘Helper’ functions in C++

Overhead is not an issue, namespaces have some advantages though You can reopen a namespace in another header, grouping things more logically while keeping compile dependencies low You can use namespace aliasing to your advantage (debug/release, platform specific helpers, ….) e.g. I’ve done stuff like namespace LittleEndianHelper { void Function(); } namespace BigEndianHelper { void … Read more

JSON to Javascript Class

Just assign to an instance: static from(json){ return Object.assign(new Student(), json); } So you can do: const student = Student.from({ name: “whatever” }); Or make it an instance method and leave away the assignemnt: applyData(json) { Object.assign(this, json); } So you can: const student = new Student; student.applyData({ name: “whatever” }); It could also be … Read more

How to create routes with FastAPI within a class

This can be done by using an APIRouter‘s add_api_route method: from fastapi import FastAPI, APIRouter class Hello: def __init__(self, name: str): self.name = name self.router = APIRouter() self.router.add_api_route(“/hello”, self.hello, methods=[“GET”]) def hello(self): return {“Hello”: self.name} app = FastAPI() hello = Hello(“World”) app.include_router(hello.router) Example: $ curl 127.0.0.1:5000/hello {“Hello”:”World”} add_api_route‘s second argument (endpoint) has type Callable[…, Any], … Read more